<?php

use Illuminate\Database\Capsule\Manager as DB;
use app\modules\Admin\models\twostagelogModel;
use app\modules\Admin\models\twostageModel;
use app\modules\Admin\models\twostagerewardModel;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;


class ExportController extends CoreController
{

    public function init()
    {
        if (!$this->isCli()) {
            throw new Exception("Go to cli please!", '303');
        }
        parent::init();
    }

    #[导出会员]
    public function memberAction()
    {
        $path      = $this->get('path');
        $type      = $this->get('type');
        $keywords  = $this->get('keywords');
        $search    = [];
        $condition = [];
        $query = (new memberModel)->withTrashed();
        if ($keywords) {
            array_push($search, [$type, '=', $keywords]);
        }
        $startOn = $this->get('startOn');
        if (!empty($startOn)) {
            $query = $query->where('created_at','>=', $startOn);
        }
        $endOn = $this->get('endOn');
        if (!empty($endOn)) {
            $query = $query->where('created_at','<=', $endOn);
        }

        if (!empty($search)) {
            $query = $query->where(function ($query) use ($search) {
                foreach ($search as $v) {
                    if (isset($v[3]) && strtolower($v[3]) == 'or') {
                        $query = $query->orWhere([$v]);
                    } else {
                        $query = $query->where([$v]);
                    }
                }
            });
        }
        if (!empty($condition)) {
            $query = $query->where($condition);
        }
        $query   = $query->orderBy('id', 'desc');

        $dataset = [];
        $query->select('id', 'nickname', 'parent_member_id', 'phone', 'level', 'money', 'score', 'total_income', 'total_consume', 'team_consume', 'status', 'created_at')
            ->chunk(1000, function ($members) use (&$dataset) {
                foreach ($members as $k => $v) {
                    array_push($dataset, [
                        'id'               => $v->id,
                        'nickname'         => $v->nickname . ($v->deleted_at ? '(已删除)' : ''),
                        'parent_member_id' => $v->parent_member_id,
                        'phone'            => $v->phone,
                        'level_info'       => $v->level_info ? $v->level_info->name : '普通会员',
                        'money'            => $v->money,
                        'score'            => $v->score,
                        'total_income'     => $v->total_income,
                        'total_consume'    => $v->total_consume,
                        'team_consume'     => $v->team_consume,
                        'status'           => $v->deleted_at ? '已删除' : ($v->status == 'normal' ? '正常' : ($v->status == 'frozen' ? '冻结' : '锁定')),
                        'created_at'       => $v->created_at ? $v->created_at->__toString() : '-',
                    ]);
                }
            });
        $title = ['ID', '名称', '推荐人ID', '手机号', '身份', '余额', '积分', '累计佣金', '消费金额', '团队业绩', '状态', '加入时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出商城会员]
    public function shopmemberAction()
    {
        $path      = $this->get('path');
        $type      = $this->get('type');
        $keywords  = $this->get('keywords');
        $search    = [];
        $condition = [];
        $query = (new memberModel)->withTrashed();
        if ($keywords) {
            array_push($search, [$type, '=', $keywords]);
        }
        $startOn = $this->get('startOn');
        if (!empty($startOn)) {
            $query = $query->where('created_at','>=', $startOn);
        }
        $endOn = $this->get('endOn');
        if (!empty($endOn)) {
            $query = $query->where('created_at','<=', $endOn);
        }
        $status = $this->get('status');
        if (!empty($status)) {
            if($status=='deleted'){
                $query = $query->whereNotNull('deleted_at');
            }else{
                $query = $query->whereNull('deleted_at');
                array_push($condition, ['status', '=', $status]);
            }
        }
        if (!empty($search)) {
            $query = $query->where(function ($query) use ($search) {
                foreach ($search as $v) {
                    if (isset($v[3]) && strtolower($v[3]) == 'or') {
                        $query = $query->orWhere([$v]);
                    } else {
                        $query = $query->where([$v]);
                    }
                }
            });
        }
        if (!empty($condition)) {
            $query = $query->where($condition);
        }
        $query   = $query->orderBy('id', 'desc');

        $dataset = [];
        $query->select('id', 'nickname', 'status', 'login_times', 'logined_at', 'created_at', 'deleted_at')
              ->chunk(1000, function ($members) use (&$dataset) {
                  foreach ($members as $k => $v) {
                      array_push($dataset, [
                          'id'               => $v->id,
                          'nickname'         => $v->nickname . ($v->deleted_at ? '(已删除)' : ''),
                          'status'           => $v->deleted_at ? '已删除' : ($v->status == 'normal' ? '正常' : ($v->status == 'frozen' ? '冻结' : '锁定')),
                          'login_times'      => $v->login_times,
                          'logined_at'       => $v->logined_at ? carbon($v->logined_at)->format('Y-m-d H:i:s') : '-',
                          'created_at'       => $v->created_at ? $v->created_at->__toString() : '-',
                      ]);
                  }
              });
        $title = ['ID', '名称', '状态', '登陆次数', '最近登陆时间', '加入时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[关系变更记录]
    public function relationAction()
    {
        $params      = $this->pageParam;
        $rewardModel = (new memberrelationModel())->newQuery();
        $query       = $rewardModel->with(['member'])->orderByDesc('created_at');
        if (isset($params['startOn']) && !empty($params['startOn'])) {
            $query = $query->where('created_at','>=', $params['startOn']);
        }
        if (isset($params['endOn']) && !empty($params['endOn'])) {
            $query = $query->where('created_at','<=', $params['endOn']);
        }
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            switch ($params['type']) {
                case 'member_id':
                    $query = $query->where('member_id', $params['keywords']);
                    break;
                case 'phone':
                    $member_id = memberModel::query()->where('phone', $params['keywords'])->value('id');
                    $query     = $query->where('member_id', $member_id);
                    break;
                case 'nickname':
                    $member_ids = memberModel::query()->where('nickname', 'like', "%{$params['keywords']}%")->pluck('id');
                    $query      = $query->whereIn('member_id', $member_ids);
                    break;
                case 'before_pid':
                    $query = $query->where('before_pid', $params['keywords']);
                    break;
                case 'after_pid':
                    $query = $query->where('after_pid', $params['keywords']);
                    break;
            }
        }
        $query   = $query->orderBy('id', 'desc');

        $dataset = [];
        $query->select('id', 'created_at', 'member_id', 'before_pid', 'after_pid', 'remark', 'oper_type', 'oper_id')
            ->chunk(1000, function ($members) use (&$dataset) {
                foreach ($members as $k => $v) {
                    array_push($dataset, [
                        'id'               => $v->id,
                        'created_at'       => is_object($v->created_at) ? $v->created_at->__toString() : $v->created_at,
                        'member_id'        => $v->member_id,
                        'agent_name'       => $v->member['nickname'],
                        'agent_phone'      => $v->member['phone'],
                        'before_pid'       => $v->before_pid,
                        'after_pid'        => $v->after_pid,
                        'remark'           => $v->remark,
                        'oper_type'        => $v->oper_type,
                        'oper_id'          => $v->oper_id,
                    ]);
                }
            });
        $title = ['ID', '变更时间', '会员ID', '会员名称', '会员电话', '变更前上级', '变更后上级', '备注', '操作人', '操作人ID'];
        $this->exportExcel($title, $dataset, $params['path']);
        echo 'Done';
    }

    #[账号合并记录]
    public function mergelogAction()
    {
        $params      = $this->pageParam;
        $rewardModel = (new membermergeModel())->newQuery();
        $query       = $rewardModel->with(['target'])->orderByDesc('created_at');
        if (isset($params['startOn']) && !empty($params['startOn'])) {
            $query = $query->where('created_at','>=', $params['startOn']);
        }
        if (isset($params['endOn']) && !empty($params['endOn'])) {
            $query = $query->where('created_at','<=', $params['endOn']);
        }
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            switch ($params['type']) {
                case 'source_id':
                    $query = $query->where('source_id', $params['keywords']);
                    break;
                case 'member_id':
                    $query = $query->where('target_id', $params['keywords']);
                    break;
                case 'phone':
                    $member_id = memberModel::query()->where('phone', $params['keywords'])->value('id');
                    $query     = $query->where('target_id', $member_id);
                    break;
                case 'nickname':
                    $member_ids = memberModel::query()->where('nickname', 'like', "%{$params['keywords']}%")->pluck('id');
                    $query      = $query->whereIn('target_id', $member_ids);
                    break;
            }
        }
        $query   = $query->orderBy('id', 'desc');

        $dataset = [];
        $query->select('id', 'created_at', 'target_id', 'source_id', 'remark', 'oper_type', 'oper_id')
            ->chunk(1000, function ($members) use (&$dataset) {
                foreach ($members as $k => $v) {
                    array_push($dataset, [
                        'id'               => $v->id,
                        'created_at'       => is_object($v->created_at) ? $v->created_at->__toString() : $v->created_at,
                        'target_id'        => $v->target_id,
                        'source_id'        => $v->source_id,
                        'target_name'      => $v->target['nickname'],
                        'target_phone'     => $v->target['phone'],
                        'remark'           => $v->remark,
                        'oper_type'        => $v->oper_type,
                        'oper_id'          => $v->oper_id,
                    ]);
                }
            });
        $title = ['ID', '合并时间', '目标账号ID', '源账号ID', '会员名称', '会员电话', '备注', '操作人', '操作人ID'];
        $this->exportExcel($title, $dataset, $params['path']);
        echo 'Done';
    }

    #[导出代理]
    public function agentAction()
    {
        $query     = (new memberModel)->withTrashed()->where('level', '>', 1);
        $path      = $this->get('path');
        $type      = $this->get('type');
        $keywords  = $this->get('keywords');
        $search    = [];
        $condition = [];
        if ($keywords) {
            array_push($search, [$type, '=', $keywords]);
        }
        $level = $this->get('level');
        if ($level) {
            array_push($condition, ['level', '=', $level]);
        }
        $startOn = $this->get('startOn');
        if (!empty($startOn)) {
            $query = $query->where('created_at','>=', $startOn);
        }
        $endOn = $this->get('endOn');
        if (!empty($endOn)) {
            $query = $query->where('created_at','<=', $endOn);
        }
        if (!empty($search)) {
            $query = $query->where(function ($query) use ($search) {
                foreach ($search as $v) {
                    if (isset($v[3]) && strtolower($v[3]) == 'or') {
                        $query = $query->orWhere([$v]);
                    } else {
                        $query = $query->where([$v]);
                    }
                }
            });
        }
        if (!empty($condition)) {
            $query = $query->where($condition);
        }
        $query   = $query->orderBy('id', 'desc');
        $dataset = [];
        $query->select('id', 'nickname', 'parent_member_id', 'level', 'money', 'score', 'total_income', 'total_consume', 'team_consume', 'status', 'created_at')
            ->chunk(1000, function ($members) use (&$dataset) {
                foreach ($members as $k => $v) {
                    array_push($dataset, [
                        'id'               => $v->id,
                        'nickname'         => $v->nickname . ($v->deleted_at ? '(已删除)' : ''),
                        'parent_member_id' => $v->parent_member_id,
                        'phone'            => $v->phone,
                        'level_info'       => $v->level_info ? $v->level_info->name : '普通会员',
                        'money'            => $v->money,
                        'score'            => $v->score,
                        'total_income'     => $v->total_income,
                        'total_consume'    => $v->total_consume,
                        'team_consume'     => $v->team_consume,
                        'status'           => $v->deleted_at ? '已删除' : ($v->status == 'normal' ? '正常' : ($v->status == 'frozen' ? '冻结' : '锁定')),
                        'created_at'       => $v->created_at ?? $v->created_at->__toString(),
                    ]);
                }
            });
        $title = ['ID', '名称', '推荐人ID', '手机号', '身份', '余额', '积分', '累计佣金', '消费金额', '团队业绩', '状态', '加入时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出代理分红]
    public function agentrewardAction()
    {
        $query     = (new agentrewardModel)->with(['agent', 'buyer', 'order', 'orderItem'])->orderByDesc('created_at');
        $path      = $this->get('path');
        $mode      = $this->get('mode');
        $type      = $this->get('type');
        $keywords  = $this->get('keywords');
        $search    = [];
        $condition = [];
        if ($mode != 'all') {
            switch ($mode) {
                case 'waiting':
                    $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    break;
                case 'accounted':
                    $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    break;
                case 'cancel':
                    $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    break;
                case 'back':
                    $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_BACK);
                    break;
            }
        }
        if ($keywords) {
            switch ($type) {
                case 'agent_id':
                    $query = $query->where('agent_id', $keywords);
                    break;
                case 'agent_phone':
                    $agent_id = memberModel::query()->where('phone', $keywords)->value('id');
                    $query    = $query->where('agent_id', $agent_id);
                    break;
                case 'order_id':
                    $query = $query->where('order_id', $keywords);
                    break;
                case 'order_sn':
                    $order_id = orderModel::query()->where('order_sn', $keywords)->value('id');
                    $query    = $query->where('order_id', $order_id);
                    break;
                case 'buyer_id':
                    $query = $query->where('buyer_id', $keywords);
                    break;
                case 'buyer_phone':
                    $buyer_id = memberModel::query()->where('phone', $keywords)->value('id');
                    $query    = $query->where('buyer_id', $buyer_id);
                    break;
                case 'goods_id':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $keywords)->pluck('id')->toArray());
                    break;
                case 'goods_title':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $class = $this->get('class');
        if ($class) {
            array_push($condition, ['class', '=', $class]);
        }
        $startOn = $this->get('startOn');
        if (!empty($startOn)) {
            array_push($condition, ['created_at', '>=', $startOn.' 00:00:00']);
        }
        $endOn = $this->get('endOn');
        if (!empty($endOn)) {
            array_push($condition, ['created_at', '<=', $endOn.' 23:59:59']);
        }
        if (!empty($search)) {
            $query = $query->where(function ($query) use ($search) {
                foreach ($search as $v) {
                    if (isset($v[3]) && strtolower($v[3]) == 'or') {
                        $query = $query->orWhere([$v]);
                    } else {
                        $query = $query->where([$v]);
                    }
                }
            });
        }
        if (!empty($condition)) {
            $query = $query->where($condition);
        }
        $query   = $query->orderBy('id', 'desc');
        $dataset = [];
        $query->chunk(1000, function ($data) use (&$dataset) {
                foreach ($data as $k => $v) {
                    array_push($dataset, [
                        'id'               => $v->id,
                        'order_id'         => $v->order_id,
                        'order_sn'         => $v->order->order_sn,
                        'goods_title'      => $v->orderItem->goods_title,
                        'goods_id'         => $v->orderItem->goods_id,
                        'goods_sku_text'   => $v->orderItem->goods_sku_text,
                        'goods_num'        => $v->orderItem->goods_num,
                        'buyer_id'         => $v->buyer->id,
                        'buyer_name'       => $v->buyer->nickname,
                        'buyer_phone'      => $v->buyer->phone,
                        'agent_id'         => $v->agent->id,
                        'agent_name'       => $v->agent->nickname,
                        'agent_phone'      => $v->agent->phone,
                        'agent_level'      => $v->agent_level,
                        'class_text'       => $v->class_text,
                        'commission_level' => $v->commission_level,
                        'pay_price'        => $v->pay_price,
                        'commission'       => $v->commission,
                        'status_name'      => $v->status_name,
                        'created_at'       => $v->created_at ? $v->created_at->__toString() : '',
                        'updated_at'       => $v->updated_at ? $v->updated_at->__toString() : '',
                    ]);
                }
            });
        $title = ['ID', '订单ID', '订单编号', '商品名称', '商品ID', '商品款式', '商品数量', '下单人ID', '下单人名称', '下单人电话', '代理会员ID',
            '代理会员昵称', '代理会员电话', '代理级别', '佣金类别', '分佣层级', '订单金额', '分红金额', '入账状态', '分红时间', '变动时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出所有分红]
    public function allrewardAction()
    {
        $path   = $this->get('path');
        $params = $this->pageParam;
        $agentRewardModel = agentrewardModel::query()->select(['id','order_id','order_item_id','buyer_id','commission_order_id',
            'agent_id as daili_id','type','class','commission','original_commission',
            'commission_level','agent_level as level','commission_rules','status','created_at','updated_at', DB::raw ('"agent" AS model_name')]);
        $gudongRerwardModel = gudongrewardModel::query()->select(['id','order_id','order_item_id','buyer_id','commission_order_id',
            'gudong_id as daili_id','type','class','commission','original_commission',
            'commission_level','agent_level as level','commission_rules','status','created_at','updated_at', DB::raw ('"gudong" AS model_name')]);
        $qudaiRewardModel = qudairewardModel::query()->select(['id','order_id','order_item_id','buyer_id','commission_order_id',
            'qudai_id as daili_id','type','class','commission','original_commission',
            'commission_level','area_level as level','commission_rules','status','created_at','updated_at', DB::raw ('"qudai" AS model_name')]);
        $tuikeRewardModel = tuikerewardModel::query()->select(['id','order_id','order_item_id','buyer_id','commission_order_id',
            'tuike_id as daili_id','type','class','commission','original_commission',
            'commission_level','tuike_level as level','commission_rules','status','created_at','updated_at', DB::raw ('"tuike" AS model_name')]);

        if(isset($params['mode']) && $params['mode'] != 'all'){
            switch ($params['mode']){
                case 'waiting':
                    $agentRewardModel = $agentRewardModel->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    $gudongRerwardModel = $gudongRerwardModel->where('status', gudongrewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    $qudaiRewardModel = $qudaiRewardModel->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    $tuikeRewardModel = $tuikeRewardModel->where('status', tuikerewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    break;
                case 'accounted':
                    $agentRewardModel = $agentRewardModel->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    $gudongRerwardModel = $gudongRerwardModel->where('status', gudongrewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    $qudaiRewardModel = $qudaiRewardModel->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    $tuikeRewardModel = $tuikeRewardModel->where('status', tuikerewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    break;
                case 'cancel':
                    $agentRewardModel = $agentRewardModel->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    $gudongRerwardModel = $gudongRerwardModel->where('status', gudongrewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    $qudaiRewardModel = $qudaiRewardModel->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    $tuikeRewardModel = $tuikeRewardModel->where('status', tuikerewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    break;
                case 'back':
                    $agentRewardModel = $agentRewardModel->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_BACK);
                    $gudongRerwardModel = $gudongRerwardModel->where('status', gudongrewardModel::COMMISSION_REWARD_STATUS_BACK);
                    $qudaiRewardModel = $qudaiRewardModel->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_BACK);
                    $tuikeRewardModel = $tuikeRewardModel->where('status', tuikerewardModel::COMMISSION_REWARD_STATUS_BACK);
                    break;
            }
        }
        if(isset($params['start_on']) && !empty($params['start_on'])){
            $agentRewardModel = $agentRewardModel->where('created_at', '>=', $params['start_on']);
            $gudongRerwardModel = $gudongRerwardModel->where('created_at', '>=', $params['start_on']);
            $qudaiRewardModel = $qudaiRewardModel->where('created_at', '>=', $params['start_on']);
            $tuikeRewardModel = $tuikeRewardModel->where('created_at', '>=', $params['start_on']);
        }
        if(isset($params['end_on']) && !empty($params['end_on'])){
            $agentRewardModel = $agentRewardModel->where('created_at', '<=', $params['end_on']);
            $gudongRerwardModel = $gudongRerwardModel->where('created_at', '<=', $params['end_on']);
            $qudaiRewardModel = $qudaiRewardModel->where('created_at', '<=', $params['end_on']);
            $tuikeRewardModel = $tuikeRewardModel->where('created_at', '<=', $params['end_on']);
        }
        if(isset($params['keywords']) && !empty($params['keywords'])){
            if(isset($params['keywordsType']) && !empty($params['keywordsType'])){
                switch ($params['keywordsType']){
                    case 'daili_id':
                        $agentRewardModel = $agentRewardModel->where('agent_id', $params['keywords']);
                        $gudongRerwardModel = $gudongRerwardModel->where('gudong_id', $params['keywords']);
                        $qudaiRewardModel = $qudaiRewardModel->where('qudai_id', $params['keywords']);
                        $tuikeRewardModel = $tuikeRewardModel->where('tuike_id', $params['keywords']);
                        break;
                    case 'daili_phone':
                        $agentRewardModel = $agentRewardModel->whereIn('agent_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $gudongRerwardModel = $gudongRerwardModel->whereIn('gudong_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $qudaiRewardModel = $qudaiRewardModel->whereIn('qudai_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $tuikeRewardModel = $tuikeRewardModel->whereIn('tuike_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        break;
                    case 'order_id':
                        $agentRewardModel = $agentRewardModel->where('order_id', $params['keywords']);
                        $gudongRerwardModel = $gudongRerwardModel->where('order_id', $params['keywords']);
                        $qudaiRewardModel = $qudaiRewardModel->where('order_id', $params['keywords']);
                        $tuikeRewardModel = $tuikeRewardModel->where('order_id', $params['keywords']);
                        break;
                    case 'order_sn':
                        $agentRewardModel = $agentRewardModel->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $gudongRerwardModel = $gudongRerwardModel->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $qudaiRewardModel = $qudaiRewardModel->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $tuikeRewardModel = $tuikeRewardModel->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        break;
                    case 'buyer_id':
                        $agentRewardModel = $agentRewardModel->where('buyer_id', $params['keywords']);
                        $gudongRerwardModel = $gudongRerwardModel->where('buyer_id', $params['keywords']);
                        $qudaiRewardModel = $qudaiRewardModel->where('buyer_id', $params['keywords']);
                        $tuikeRewardModel = $tuikeRewardModel->where('buyer_id', $params['keywords']);
                        break;
                    case 'buyer_phone':
                        $agentRewardModel = $agentRewardModel->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $gudongRerwardModel = $gudongRerwardModel->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $qudaiRewardModel = $qudaiRewardModel->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $tuikeRewardModel = $tuikeRewardModel->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        break;
                    case 'goods_id':
                        $agentRewardModel = $agentRewardModel->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $params['keywords'])->pluck('id')->toArray());
                        $gudongRerwardModel = $gudongRerwardModel->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $params['keywords'])->pluck('id')->toArray());
                        $qudaiRewardModel = $qudaiRewardModel->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $params['keywords'])->pluck('id')->toArray());
                        $tuikeRewardModel = $tuikeRewardModel->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $params['keywords'])->pluck('id')->toArray());
                        break;
                    case 'goods_title':
                        $agentRewardModel = $agentRewardModel->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $gudongRerwardModel = $gudongRerwardModel->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $qudaiRewardModel = $qudaiRewardModel->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        $tuikeRewardModel = $tuikeRewardModel->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                        break;
                }
            }
        }
        $unionQuery = $agentRewardModel->unionAll($gudongRerwardModel)->unionAll($qudaiRewardModel)->unionAll($tuikeRewardModel);
        $querySql = $unionQuery->toSql();
        $query = DB::table(DB::raw("($querySql) as unionSearch"))->mergeBindings($unionQuery->getQuery())->orderBy('created_at', 'DESC');
        $dataset = [];
        $query->chunk(10, function ($data) use (&$dataset) {
            foreach ($data as $k => $v) {
                $order = \app\modules\Admin\models\orderModel::query()->where('id', $v->order_id)->select(['id', 'order_sn'])->first();
                $orderItem = \app\modules\Admin\models\orderItemModel::query()->where('id', $v->order_item_id)->select(['id', 'goods_id', 'goods_title', 'goods_sku_text', 'goods_num'])->first();
                $buyer = memberModel::query()->where('id', $v->buyer_id)->select(['id', 'phone', 'nickname', 'realname'])->first();
                $bonus = memberModel::query()->where('id', $v->daili_id)->select(['id', 'phone', 'nickname', 'realname'])->first();
                switch ($v->status) {
                    case gudongrewardModel::COMMISSION_REWARD_STATUS_BACK:
                        $v->status_name = '已退回';
                        break;
                    case gudongrewardModel::COMMISSION_REWARD_STATUS_WAITING:
                        $v->status_name = '待入账';
                        break;
                    case gudongrewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED:
                        $v->status_name = '已入账';
                        break;
                    case gudongrewardModel::COMMISSION_REWARD_STATUS_CANCEL:
                        $v->status_name = '已取消';
                        break;
                    default:
                        $v->status_name = '';
                }
                $v->fenghong_type = '其他佣金';
                switch ($v->class) {
                    case 'pingjifenhong':
                        $v->fenghong_type = '平级奖励';
                        break;
                    case 'jichafenhong':
                        $v->fenghong_type = '级差分红';
                        break;
                    case 'gudongfenhong':
                        $v->fenghong_type = '股东分红';
                        break;
                    case 'qudaifenhong':
                        $v->fenghong_type = '区域经销商分红';
                        break;
                    case 'tuikefenhong':
                        $v->fenghong_type = '推客佣金';
                        break;
                }

                array_push($dataset, [
                    'id'               => $v->id,
                    'order_id'         => $v->order_id,
                    'order_sn'         => $order->order_sn,
                    'goods_title'      => $orderItem->goods_title,
                    'goods_id'         => $orderItem->goods_id,
                    'goods_sku_text'   => $orderItem->goods_sku_text,
                    'goods_num'        => $orderItem->goods_num,
                    'buyer_id'         => $buyer->id,
                    'buyer_name'       => $buyer->nickname,
                    'buyer_phone'      => $buyer->phone,
                    'agent_id'         => $bonus->id,
                    'agent_name'       => $bonus->nickname,
                    'agent_phone'      => $bonus->phone,
                    'agent_level'      => $v->level,
                    'class_text'       => $v->fenghong_type,
                    'commission_level' => $v->commission_level,
                    'pay_price'        => $v->pay_price,
                    'commission'       => $v->commission,
                    'status_name'      => $v->status_name,
                    'created_at'       => is_object($v->created_at) ? $v->created_at->__toString() : $v->created_at,
                    'updated_at'       => is_object($v->updated_at) ? $v->updated_at->__toString() : $v->created_at,
                ]);
            }
        });
        $title = ['ID', '订单ID', '订单编号', '商品名称', '商品ID', '商品款式', '商品数量', '下单人ID', '下单人名称', '下单人电话', '代理会员ID',
            '代理会员昵称', '代理会员电话', '代理级别', '佣金类别', '分佣层级', '订单金额', '分红金额', '入账状态', '分红时间', '变动时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出订单]
    public function orderAction()
    {
        $path      = $this->get('path');
        $search    = [];
        $condition = [];
        $model = (new orderModel)->with(['member', 'item']);
        $startOn   = $this->get('startOn');
        if (!empty($startOn)) {
            $model = $model->where('created_at','>=', $startOn);
        }
        $endOn = $this->get('endOn');
        if (!empty($endOn)) {
            $model = $model->where('created_at','<=', $endOn);
        }
        $mode  = $this->get('mode');

        switch ($mode) {
            case 'canceled':
                $model = $model->where('status', orderModel::STATUS_CANCEL);
                break;
            case 'closed':
                $model = $model->where('status', orderModel::STATUS_INVALID);
                break;
            case 'nopay':
                $model = $model->where('status', orderModel::STATUS_NOPAY);
                break;
            case 'paid':
                $model = $model->where('status', orderModel::STATUS_PAYED);
                break;
            case 'nosend':
                $model = $model->where('status', orderModel::STATUS_PAYED)->whereExists(function ($query) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->where('dispatch_status', orderitemModel::DISPATCH_STATUS_NOSEND)
                        ->whereNotIn('refund_status', [orderitemModel::REFUND_STATUS_OK, orderitemModel::REFUND_STATUS_FINISH])
                        ->whereNotIn('aftersale_status', [orderitemModel::AFTERSALE_STATUS_AFTERING, orderitemModel::AFTERSALE_STATUS_OK]);
                });
                break;
            case 'send':
                $model = $model->where('status', orderModel::STATUS_PAYED)->whereExists(function ($query) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->where('dispatch_status', orderitemModel::DISPATCH_STATUS_SENDED)
                        ->whereNotIn('refund_status', [orderitemModel::REFUND_STATUS_OK, orderitemModel::REFUND_STATUS_FINISH])
                        ->whereNotIn('aftersale_status', [orderitemModel::AFTERSALE_STATUS_AFTERING, orderitemModel::AFTERSALE_STATUS_OK]);
                });
                break;
            case 'nocomment':
                $model = $model->where('status', orderModel::STATUS_PAYED)->whereExists(function ($query) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->where('dispatch_status', orderitemModel::DISPATCH_STATUS_GETED)
                        ->where('comment_status', orderitemModel::COMMENT_STATUS_NO)
                        ->whereNotIn('refund_status', [orderitemModel::REFUND_STATUS_OK, orderitemModel::REFUND_STATUS_FINISH])
                        ->whereNotIn('aftersale_status', [orderitemModel::AFTERSALE_STATUS_AFTERING, orderitemModel::AFTERSALE_STATUS_OK]);
                });
                break;
            case 'finished':
                $model = $model->where('status', orderModel::STATUS_FINISH);
                break;
            case 'aftersale':
                $model = $model->where('status', orderModel::STATUS_PAYED)->whereExists(function ($query) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->where('aftersale_status', '<>', orderitemModel::AFTERSALE_STATUS_NOAFTER);
                });
                break;
            case 'refund':
                $model = $model->where('status', orderModel::STATUS_PAYED)->whereExists(function ($query) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->where('refund_status', '<>', orderitemModel::REFUND_STATUS_NOREFUND);
                });
                break;
        }
        $keywordsType = $this->get('type');
        $keywords     = $this->get('keywords');
        if ($keywords !== '') {
            switch ($keywordsType) {
                case 'order_id':
                    $model = $model->where('id', $keywords);
                    break;
                case 'order_sn':
                    $model = $model->where('order_sn', 'like', "%{$keywords}%");
                    break;
                case 'member_id':
                    $model = $model->where('member_id', $keywords);
                    break;
                case 'member_phone':
                    $model = $model->whereIn('member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                    break;
                case 'customer_id':
                    $model = $model->where('customer_id', $keywords);
                    break;
                case 'consignee':
                    $model = $model->where('consignee', $keywords);
                    break;
                case 'consignee_phone':
                    $model = $model->where('phone', 'like', "%{$keywords}%");
                    break;
            }
        }
        $goods = $this->get('goods');
        if ($goods !== '') {
            if (is_numeric($goods)) {
                $model = $model->whereExists(function ($query) use ($goods) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->where('goods_id', $goods);
                });
            } else {
                $model = $model->whereExists(function ($query) use ($goods) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->whereIn('goods_id', DB::table('goods')->where('dianpu_id','=',0)->where('title', 'like', "%{$goods}%")->limit(20)->pluck('id'));
                });
            }
        }
        $appends = ['status_code', 'status_name'];
        $query   = $model;
        if (!empty($search)) {
            $query = $query->where(function ($query) use ($search) {
                foreach ($search as $v) {
                    if (isset($v[3]) && strtolower($v[3]) == 'or') {
                        $query = $query->orWhere([$v]);
                    } else {
                        $query = $query->where([$v]);
                    }
                }
            });
        }
        if (!empty($condition)) {
            $query = $query->where($condition);
        }
        $query   = $query->orderBy('id', 'desc');
        $dataset = [];
        $query->select('*')
            ->chunk(1000, function ($rows) use (&$dataset) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $rows = $rows->append($append);
                    }
                }
                foreach ($rows as $k => $v) {
                    $hlb_order_no = '';
                    if($v['pay_type']=='helibao' && $v['status']>0){
                        $hlb_order_no = helibaoorderModel::query()->where('order_sn', $v['order_sn'])->where('transaction_no', '<>', '')->value('pay_order_no');
                    }
                    $ext_arr         = $v->ext_arr;
                    if (isset($ext_arr['combo']) && $ext_arr['combo'] == 1) {
                        $goods_combo_txt = $v->item[0]->goods_combo;
                        if (!empty($goods_combo_txt)) {
                            $goods_combo = json_decode($goods_combo_txt, true);
                            $combo_goods = '';
                            foreach ($goods_combo['goods'] as $onecombogoods){
                                $combo_goods .= $onecombogoods['goods_title'] . "\r\n" . $onecombogoods['goods_sku_text'] . '*' . $onecombogoods['goods_num'] . "\r\n";
                            }
                        }
                        array_push($dataset, [
                            'order_id'             => $v->id,
                            'order_sn'             => $v->order_sn,
                            'type_text'            => $v->type,
                            'status_text'          => $v->status,
                            'pay_type_text'        => $v->pay_type,
                            'ordertime_text'       => $v->created_at,
                            'paytime_text'         => date('Y-m-d H:i:s', $v->paytime),
                            'platform_text'        => $v->platform,
                            'user_nickname'        => $v->member->nickname,
                            'user_phone'           => $v->member->phone,
                            'total_amount'         => $v->total_amount,
                            'discount_fee'         => $v->discount_fee,
                            'score_fee'            => $v->score_fee,
                            'pay_fee'              => $v->item[0]->pay_price,
                            'cost_price'           => '',
                            'remark'               => $v->remark,
                            'memo'                 => $v->memo,
                            'goods_title'          => $v->item[0]->goods_title,
                            'goods_original_price' => $v->item[0]->goods_original_price,
                            'goods_price'          => $v->item[0]->goods_price,
                            'goods_sku_text'       => $combo_goods,
                            'goods_num'            => $v->item[0]->goods_num,
                            'refund_fee'           => $v->item[0]->refund_fee,
                            'refund_msg'           => $v->item[0]->refund_msg,
                            'consignee_name'       => $v->consignee,
                            'consignee_phone'      => $v->phone,
                            'consignee_province'   => $v->province_name,
                            'consignee_city'       => $v->city_name,
                            'consignee_area'       => $v->area_name,
                            'consignee_address'    => $v->address,
                            'express_name'         => $v->item[0]->express_name,
                            'express_no'           => $v->item[0]->express_no,
                            'hlb_order_no'         => $hlb_order_no,
							'shouhuo_time'         => is_object($v->updated_at) ? $v->updated_at->__toString() : $v->created_at,
                        ]);
                    }else {
                        foreach ($v->item as $item) {
                            array_push($dataset, [
                                'order_id'             => $v->id,
                                'order_sn'             => $v->order_sn,
                                'type_text'            => $v->type,
                                'status_text'          => $v->status,
                                'pay_type_text'        => $v->pay_type,
                                'ordertime_text'       => $v->created_at,
                                'paytime_text'         => date('Y-m-d H:i:s', $v->paytime),
                                'platform_text'        => $v->platform,
                                'user_nickname'        => $v->member->nickname,
                                'user_phone'           => $v->member->phone,
                                'total_amount'         => $v->total_amount,
                                'discount_fee'         => $v->discount_fee,
                                'score_fee'            => $v->score_fee,
                                'pay_fee'              => $item->pay_price,
                                'cost_price'           => $item->cost_price,
                                'remark'               => $v->remark,
                                'memo'                 => $v->memo,
                                'goods_title'          => $item->goods_title,
                                'goods_original_price' => $item->goods_original_price,
                                'goods_price'          => $item->goods_price,
                                'goods_sku_text'       => $item->goods_sku_text,
                                'goods_num'            => $item->goods_num,
                                'refund_fee'           => $item->refund_fee,
                                'refund_msg'           => $item->refund_msg,
                                'consignee_name'       => $v->consignee,
                                'consignee_phone'      => $v->phone,
                                'consignee_province'   => $v->province_name,
                                'consignee_city'       => $v->city_name,
                                'consignee_area'       => $v->area_name,
                                'consignee_address'    => $v->address,
                                'express_name'         => $item->express_name,
                                'express_no'           => $item->express_no,
                                'hlb_order_no'         => $hlb_order_no,
								'shouhuo_time'         => is_object($v->updated_at) ? $v->updated_at->__toString() : $v->created_at,
                            ]);
                        }
                    }
                }
            });
        $title = ['ID', '订单号', '订单类型', '订单状态', '支付类型', '下单时间', '支付时间', '交易平台', '用户姓名', '手机号', '订单总金额', '优惠金额',
            '积分支付数量', '实际支付金额', '成本价', '用户备注', '平台备注', '商品名称', '商品原价', '商品价格', '商品规格', '商品数量', '退款金额', '退款原因',
            '收件人姓名', '收件人电话', '收货省', '收货市', '收货区', '收货地址', '快递公司', '快递单号', '合利宝单号','收货时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出待发货订单]
    public function ordernosendAction()
    {
        $path      = $this->get('path');
        $search    = [];
        $condition = [];
        $startOn   = $this->get('startOn');
        $model = (new orderModel)->with(['member', 'item']);
        if (!empty($startOn)) {
            $model = $model->where('created_at','>=', $startOn);
        }
        $endOn = $this->get('endOn');
        if (!empty($endOn)) {
            $model = $model->where('created_at','<=', $endOn);
        }
        $mode  = 'nosend';

        switch ($mode) {
            case 'nosend':
                $model = $model->where('status', orderModel::STATUS_PAYED)->whereExists(function ($query) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->where('dispatch_status', orderitemModel::DISPATCH_STATUS_NOSEND)
                        ->whereNotIn('refund_status', [orderitemModel::REFUND_STATUS_OK, orderitemModel::REFUND_STATUS_FINISH])
                        ->whereNotIn('aftersale_status', [orderitemModel::AFTERSALE_STATUS_AFTERING, orderitemModel::AFTERSALE_STATUS_OK]);
                });
                break;
        }
        $keywordsType = $this->get('type');
        $keywords     = $this->get('keywords');
        if ($keywords !== '') {
            switch ($keywordsType) {
                case 'order_id':
                    $model = $model->where('id', $keywords);
                    break;
                case 'order_sn':
                    $model = $model->where('order_sn', 'like', "%{$keywords}%");
                    break;
                case 'member_id':
                    $model = $model->where('member_id', $keywords);
                    break;
                case 'member_phone':
                    $model = $model->whereIn('member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                    break;
                case 'customer_id':
                    $model = $model->where('customer_id', $keywords);
                    break;
                case 'consignee':
                    $model = $model->where('consignee', $keywords);
                    break;
                case 'consignee_phone':
                    $model = $model->where('phone', 'like', "%{$keywords}%");
                    break;
            }
        }
        $goods = $this->get('goods');
        if ($goods !== '') {
            if (is_numeric($goods)) {
                $model = $model->whereExists(function ($query) use ($goods) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->where('goods_id', $goods);
                });
            } else {
                $model = $model->whereExists(function ($query) use ($goods) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                        ->whereIn('goods_id', DB::table('goods')->where('dianpu_id','=',0)->where('title', 'like', "%{$goods}%")->limit(20)->pluck('id'));
                });
            }
        }
        $appends = ['status_code', 'status_name'];
        $query   = $model;
        if (!empty($search)) {
            $query = $query->where(function ($query) use ($search) {
                foreach ($search as $v) {
                    if (isset($v[3]) && strtolower($v[3]) == 'or') {
                        $query = $query->orWhere([$v]);
                    } else {
                        $query = $query->where([$v]);
                    }
                }
            });
        }
        if (!empty($condition)) {
            $query = $query->where($condition);
        }
        $query   = $query->orderBy('id', 'desc');
        $dataset = [];
        $query->select('*')
            ->chunk(1000, function ($rows) use (&$dataset) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $rows = $rows->append($append);
                    }
                }
                foreach ($rows as $k => $v) {
                    $ext_arr         = $v->ext_arr;
                    if (isset($ext_arr['combo']) && $ext_arr['combo'] == 1) {
                        $goods_combo_txt = $v->item[0]->goods_combo;
                        if (is_string($goods_combo_txt)) {
                            $goods_combo = json_decode($goods_combo_txt, true);
                            $combo_goods = '';
                            foreach ($goods_combo['goods'] as $onecombogoods){
                                $combo_goods .= $onecombogoods['goods_title'] . "\r\n" . $onecombogoods['goods_sku_text'] . '*' . $onecombogoods['goods_num'] . "\r\n";
                            }
                        }
                        array_push($dataset, [
                            'order_id'           => $v->id,
                            'order_sn'           => $v->order_sn,
                            'order_item_id'      => $v->item[0]->id,
                            'type_text'          => $v->type,
                            'remark'             => $v->remark,
                            'memo'               => $v->memo,
                            'goods_title'        => $v->item[0]->goods_title,
                            'goods_sku_text'     => $combo_goods,
                            'goods_num'          => $v->item[0]->goods_num,
                            'pay_price'          => $v->item[0]->pay_price,
                            'dispatch_fee'       => $v->item[0]->dispatch_fee,
                            'dispatch_type_text' => $v->item[0]->dispatch_type_text,
                            'aftersale_refund'   => $v->item[0]->aftersale_status_text . '/' . $v->item[0]->refund_status_text,
                            'ordertime_text'     => $v->created_at,
                            'paytime_text'       => date('Y-m-d H:i:s', $v->paytime),
                            'consignee_name'     => $v->consignee,
                            'consignee_phone'    => $v->phone,
                            'consignee_province' => $v->province_name,
                            'consignee_city'     => $v->city_name,
                            'consignee_area'     => $v->area_name,
                            'consignee_address'  => $v->address,
                            'express_no'         => $v->item[0]->express_no,
                        ]);
                    }else {
                        foreach ($v->item as $item) {
                            array_push($dataset, [
                                'order_id'           => $v->id,
                                'order_sn'           => $v->order_sn,
                                'order_item_id'      => $item->id,
                                'type_text'          => $v->type,
                                'remark'             => $v->remark,
                                'memo'               => $v->memo,
                                'goods_title'        => $item->goods_title,
                                'goods_sku_text'     => $item->goods_sku_text,
                                'goods_num'          => $item->goods_num,
                                'pay_price'          => $item->pay_price,
                                'dispatch_fee'       => $item->dispatch_fee,
                                'dispatch_type_text' => $item->dispatch_type_text,
                                'aftersale_refund'   => $item->aftersale_status_text . '/' . $item->refund_status_text,
                                'ordertime_text'     => $v->created_at,
                                'paytime_text'       => date('Y-m-d H:i:s', $v->paytime),
                                'consignee_name'     => $v->consignee,
                                'consignee_phone'    => $v->phone,
                                'consignee_province' => $v->province_name,
                                'consignee_city'     => $v->city_name,
                                'consignee_area'     => $v->area_name,
                                'consignee_address'  => $v->address,
                                'express_no'         => $item->express_no,
                            ]);
                        }
                    }
                }
            });
        $title = ['ID', '订单号', '子订单Id', '订单类型', '用户备注', '平台备注', '商品名称', '商品规格', '购买数量', '商品总价', '发货费用', '发货方式', '售后/退款', '下单时间', '支付时间',
            '收件人姓名', '收件人电话', '收货省', '收货市', '收货区', '收货地址', '快递单号'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出店铺待发货订单]
    public function merchantordernosendAction()
    {
        $path      = $this->get('path');
        $search    = [];
        $condition = [];
        $startOn   = $this->get('startOn');
        $dianpu = $this->get('dianpu');
        if(empty($dianpu) || strpos($dianpu, ',') === -1){
            throw new Exception('非法导出');
        }
        list($dianpu_id, $dianpu_member, $dianpu_member_id) = explode(',',$dianpu);
        if(empty($dianpu_id) || empty($dianpu_member) || empty($dianpu_member_id)){
            throw new Exception('非法导出');
        }
        if(dianpuModel::query()->where('id', $dianpu_id)->doesntExist()){
            throw new Exception('非法店铺');
        }
        $merchant = merchantModel::query()->where('id', $dianpu_member)->where('dianpu_id', $dianpu_id)->where('member_id', $dianpu_member_id)->first();
        if(!$merchant){
            throw new Exception('非法店铺管理员');
        }
        $merchant_role = \app\modules\Admin\models\merchantrolesModel::query()->where('id', $merchant->roles_id)->first();
        if(!$merchant_role || empty($merchant_role->render_ids)){
            throw new Exception('非法权限');
        }
        $ordernosendmenus = \app\modules\Admin\models\merchantmenusModel::query()->where('controller', '=','Order')->where('actions', 'like', "%exportnosend%")->pluck('id')->toArray();
        $array_intersect = array_intersect($ordernosendmenus, explode(',',$merchant_role->render_ids));
        if (empty($array_intersect)){
            throw new Exception('非法导出权限');
        }
        $model = orderModel::query()->where('dianpu_id', $dianpu_id)->with(['member', 'item']);

        if (!empty($startOn)) {
            $model = $model->where('created_at','>=', $startOn);
        }
        $endOn = $this->get('endOn');
        if (!empty($endOn)) {
            $model = $model->where('created_at','<=', $endOn);
        }
        $mode  = 'nosend';

        switch ($mode) {
            case 'nosend':
                $model = $model->where('status', orderModel::STATUS_PAYED)->whereExists(function ($query) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                          ->where('dispatch_status', orderitemModel::DISPATCH_STATUS_NOSEND)
                          ->whereNotIn('refund_status', [orderitemModel::REFUND_STATUS_OK, orderitemModel::REFUND_STATUS_FINISH])
                          ->whereNotIn('aftersale_status', [orderitemModel::AFTERSALE_STATUS_AFTERING, orderitemModel::AFTERSALE_STATUS_OK]);
                });
                break;
        }
        $keywordsType = $this->get('type');
        $keywords     = $this->get('keywords');
        if ($keywords !== '') {
            switch ($keywordsType) {
                case 'order_id':
                    $model = $model->where('id', $keywords);
                    break;
                case 'order_sn':
                    $model = $model->where('order_sn', 'like', "%{$keywords}%");
                    break;
                case 'member_id':
                    $model = $model->where('member_id', $keywords);
                    break;
                case 'member_phone':
                    $model = $model->whereIn('member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                    break;
                case 'customer_id':
                    $model = $model->where('customer_id', $keywords);
                    break;
                case 'consignee':
                    $model = $model->where('consignee', $keywords);
                    break;
                case 'consignee_phone':
                    $model = $model->where('phone', 'like', "%{$keywords}%");
                    break;
            }
        }
        $goods = $this->get('goods');
        if ($goods !== '') {
            if (is_numeric($goods)) {
                $model = $model->whereExists(function ($query) use ($goods) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                          ->where('goods_id', $goods);
                });
            } else {
                $model = $model->whereExists(function ($query) use ($goods, $dianpu_id) {
                    $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                          ->whereIn('goods_id', DB::table('goods')->where('dianpu_id','=',$dianpu_id)->where('title', 'like', "%{$goods}%")->limit(20)->pluck('id'));
                });
            }
        }
        $appends = ['status_code', 'status_name'];
        $query   = $model;
        if (!empty($search)) {
            $query = $query->where(function ($query) use ($search) {
                foreach ($search as $v) {
                    if (isset($v[3]) && strtolower($v[3]) == 'or') {
                        $query = $query->orWhere([$v]);
                    } else {
                        $query = $query->where([$v]);
                    }
                }
            });
        }
        if (!empty($condition)) {
            $query = $query->where($condition);
        }
        $query   = $query->orderBy('id', 'desc');
        $dataset = [];
        $query->select('*')
              ->chunk(1000, function ($rows) use (&$dataset) {
                  if (!empty($appends)) {
                      foreach ($appends as $append) {
                          $rows = $rows->append($append);
                      }
                  }
                  foreach ($rows as $k => $v) {
                      $ext_arr         = $v->ext_arr;
                      if (isset($ext_arr['combo']) && $ext_arr['combo'] == 1) {
                          $goods_combo_txt = $v->item[0]->goods_combo;
                          if (is_string($goods_combo_txt)) {
                              $goods_combo = json_decode($goods_combo_txt, true);
                              $combo_goods = '';
                              foreach ($goods_combo['goods'] as $onecombogoods){
                                  $combo_goods .= $onecombogoods['goods_title'] . "\r\n" . $onecombogoods['goods_sku_text'] . '*' . $onecombogoods['goods_num'] . "\r\n";
                              }
                          }
                          array_push($dataset, [
                              'order_id'           => $v->id,
                              'order_sn'           => $v->order_sn,
                              'order_item_id'      => $v->item[0]->id,
                              'type_text'          => $v->type,
                              'remark'             => $v->remark,
                              'memo'               => $v->memo,
                              'goods_title'        => $v->item[0]->goods_title,
                              'goods_sku_text'     => $combo_goods,
                              'goods_num'          => $v->item[0]->goods_num,
                              'pay_price'          => $v->item[0]->pay_price,
                              'dispatch_fee'       => $v->item[0]->dispatch_fee,
                              'dispatch_type_text' => $v->item[0]->dispatch_type_text,
                              'aftersale_refund'   => $v->item[0]->aftersale_status_text . '/' . $v->item[0]->refund_status_text,
                              'ordertime_text'     => $v->created_at,
                              'paytime_text'       => date('Y-m-d H:i:s', $v->paytime),
                              'consignee_name'     => $v->consignee,
                              'consignee_phone'    => $v->phone,
                              'consignee_province' => $v->province_name,
                              'consignee_city'     => $v->city_name,
                              'consignee_area'     => $v->area_name,
                              'consignee_address'  => $v->address,
                              'express_no'         => $v->item[0]->express_no,
                          ]);
                      }else {
                          foreach ($v->item as $item) {
                              array_push($dataset, [
                                  'order_id'           => $v->id,
                                  'order_sn'           => $v->order_sn,
                                  'order_item_id'      => $item->id,
                                  'type_text'          => $v->type,
                                  'remark'             => $v->remark,
                                  'memo'               => $v->memo,
                                  'goods_title'        => $item->goods_title,
                                  'goods_sku_text'     => $item->goods_sku_text,
                                  'goods_num'          => $item->goods_num,
                                  'pay_price'          => $item->pay_price,
                                  'dispatch_fee'       => $item->dispatch_fee,
                                  'dispatch_type_text' => $item->dispatch_type_text,
                                  'aftersale_refund'   => $item->aftersale_status_text . '/' . $item->refund_status_text,
                                  'ordertime_text'     => $v->created_at,
                                  'paytime_text'       => date('Y-m-d H:i:s', $v->paytime),
                                  'consignee_name'     => $v->consignee,
                                  'consignee_phone'    => $v->phone,
                                  'consignee_province' => $v->province_name,
                                  'consignee_city'     => $v->city_name,
                                  'consignee_area'     => $v->area_name,
                                  'consignee_address'  => $v->address,
                                  'express_no'         => $item->express_no,
                              ]);
                          }
                      }
                  }
              });
        $title = ['ID', '订单号', '子订单Id', '订单类型', '用户备注', '平台备注', '商品名称', '商品规格', '购买数量', '商品总价', '发货费用', '发货方式', '售后/退款', '下单时间', '支付时间',
                  '收件人姓名', '收件人电话', '收货省', '收货市', '收货区', '收货地址', '快递单号'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出售后单]
    public function orderaftersaleAction()
    {
        $path      = $this->get('path');
        $query = orderaftersaleModel::query()->leftJoin('order', 'order.id', '=', 'order_aftersale.order_id')
            ->with(['order', 'member', 'item']);
        $startOn    = $this->get('startOn');
        if (!empty($start_on)) {
            $query = $query->where('order.created_at', '>=', $startOn);
        }
        $end_on = $this->get('endOn');
        if (!empty($end_on)) {
            $query = $query->where('order.created_at', '<=', $start_on);
        }
        $apply_start_on    = $this->get('applyStartOn');
        if (!empty($apply_start_on)) {
            $query = $query->where('order_aftersale.created_at', '>=', $apply_start_on);
        }
        $apply_end_on = $this->get('applyEndOn');
        if (!empty($apply_end_on)) {
            $query = $query->where('order_aftersale.created_at', '<=', $apply_end_on);
        }
        $mode = $this->get('mode');
        if ($mode != 'all') {
            $query = $query->{$mode}();
        }
        $keywordsType = $this->get('type');
        $keywords     = $this->get('keywords');
        if ($keywords !== '') {
            switch ($keywordsType) {
                case 'member_id':
                    $query = $query->where('order_aftersale.member_id', $keywords);
                    break;
                case 'member_phone':
                    $query = $query->whereIn('order_aftersale.member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                    break;
            }
        }
        $order_sn     = $this->get('orderSn');
        if($order_sn) {
            $query = $query->whereIn('order_aftersale.order_id', orderModel::where('order_sn', 'like', "%{$order_sn}%")->pluck('id'));
        }
        $query   = $query->orderBy('order_aftersale.id', 'desc');
        $dataset = [];
        $query->select(['order_aftersale.*', 'order.order_sn as order_sn', 'order.pay_type as pay_type', 'order.created_at as order_created_at'])
            ->chunk(1000, function ($rows) use (&$dataset) {
                foreach ($rows as $k => $v) {
                    $hlb_order_no = '';
                    if($v['pay_type']=='helibao'){
                        $hlb_order_no = helibaoorderModel::query()->where('order_sn', $v['order_sn'])->where('transaction_no', '<>', '')->value('pay_order_no');
                    }
                    array_push($dataset, [
                        'id'                   => $v->id,
                        'order_id'             => $v->order->id,
                        'order_sn'             => $v->order->order_sn,
                        'platform_text'        => $v->order->platform,
                        'user_nickname'        => $v->member->nickname,
                        'user_phone'           => $v->member->phone,
                        'remark'               => $v->order->remark,
                        'memo'                 => $v->order->memo,
                        'goods_title'          => $v->item->goods_title,
                        'goods_original_price' => $v->item->goods_original_price,
                        'goods_price'          => $v->item->goods_price,
                        'goods_sku_text'       => $v->item->goods_sku_text,
                        'goods_num'            => $v->item->goods_num,
                        'refund_fee'           => $v->item->refund_fee,
                        'refund_msg'           => $v->item->refund_msg,
                        'express_name'         => $v->item->express_name,
                        'express_no'           => $v->item->express_no,
                        'created_at'           => $v->created_at,
                        'hlb_order_no'         => $hlb_order_no,
                    ]);
                }
            });
        $title = ['ID', '订单ID', '订单号', '交易平台', '用户姓名', '手机号', '用户备注', '平台备注', '商品名称',
            '商品原价', '商品价格', '商品规格', '商品数量', '退款金额', '退款原因', '快递公司', '快递单号', '申请时间', '合利宝单号'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出股东]
    public function gudongAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $level=$this->get('level');

        $query = gudongModel::query()->leftjoin('member', 'member.id', '=', 'gudong.gudong_id')->with(['gudong_signin', 'member']);

        if (!empty($startOn)) {
            $query = $query->where('gudong.created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('gudong.created_at', '<=', $endOn);
        }
        if($level){
            $query = $query->where('member.level', '=', $level);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id';
                    $query = $query->where('gudong.gudong_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->where('member.phone', 'like', "%{$keywords}%");
                    break;
            }
        }
        $query = $query->orderBy('gudong.created_at', 'desc');
        $dataset = [];
        $query->select(['gudong.*','member.level', 'member.phone'])
            ->chunk(1000, function ($gudongs) use (&$dataset) {
                foreach ($gudongs as $k => $v) {
                    array_push($dataset, [
                        'id'         => $v->gudong_id,
                        'nickname'   => $v->member ? $v->member->nickname : '已删除',
                        'phone'      => $v->member ? $v->member->phone : '已删除',
                        'level_info' => $v->member ? ($v->member->level_info ? $v->member->level_info->name : '普通会员') : '已删除',
                        'status'     => $v->member ? ($v->member->status == 'normal' ? '正常' : ($v->member->status == 'frozen' ? '冻结' : '锁定')) : '已删除',
                        'created_at' => $v->created_at ?: '--',
                        'remark'     => $v->gudong_signin ? $v->gudong_signin->remark : '',
                    ]);
                }
            });
        $title = ['ID', '股东名称', '手机号', '身份', '状态', '加入时间', '备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出股东分红记录]
    public function gudongrewardAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $query = gudongrewardModel::query()->with(['gudong', 'buyerInfo', 'orderInfo', 'orderItemInfo', 'agentLevelInfo']);
        if ($mode != 'all') {
            switch ($mode) {
                case 'waiting':
                    $query = $query->where('status', gudongrewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    break;
                case 'accounted':
                    $query = $query->where('status', gudongrewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    break;
                case 'cancel':
                    $query = $query->where('status', gudongrewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    break;
                case 'back':
                    $query = $query->where('status', gudongrewardModel::COMMISSION_REWARD_STATUS_BACK);
                    break;
            }
        }
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'gudong_id':
                    $query = $query->where('gudong_id', $keywords);
                    break;
                case 'gudong_phone':
                    $query = $query->whereIn('gudong_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'order_id':
                    $query = $query->where('order_id', $keywords);
                    break;
                case 'order_sn':
                    $query = $query->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'buyer_id':
                    $query = $query->where('buyer_id', $keywords);
                    break;
                case 'buyer_phone':
                    $query = $query->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'goods_id':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $keywords)->pluck('id')->toArray());
                    break;
                case 'goods_title':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['status_name'];
        $dataset = [];
        $query->select(['id', 'order_id', 'order_item_id', 'buyer_id', 'gudong_id', 'type', 'commission', 'agent_level', 'status', 'created_at', 'updated_at'])
            ->chunk(1000, function ($gudongRewards) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $gudongRewards = $gudongRewards->append($append);
                    }
                }
                foreach ($gudongRewards as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'gudong_id'    => $v->gudong ? $v->gudong->id : '未知',
                        'gudong_name'  => $v->gudong ? $v->gudong->nickname : '未知',
                        'gudong_phone' => $v->gudong ? $v->gudong->phone : '未知',
                        'gudong_level' => $v->agentLevelInfo ? $v->agentLevelInfo->name : '暂无',
                        'buyer_id'     => $v->buyerInfo ? $v->buyerInfo->id : '未知',
                        'buyer_name'   => $v->buyerInfo ? $v->buyerInfo->nickname : '未知',
                        'buyer_phone'  => $v->buyerInfo ? $v->buyerInfo->phone : '未知',
                        'order_id'     => $v->orderInfo ? $v->orderInfo->id : '未知',
                        'order_sn'     => $v->orderInfo ? $v->orderInfo->order_sn : '未知',
                        'goods_id'     => $v->orderItemInfo ? $v->orderItemInfo->goods_id : '未知',
                        'goods_title'  => $v->orderItemInfo ? $v->orderItemInfo->goods_title : '未知',
                        'goods_sku'    => $v->orderItemInfo ? $v->orderItemInfo->goods_sku_text : '未知',
                        'goods_number' => $v->orderItemInfo ? $v->orderItemInfo->goods_num : '未知',
                        'commission'   => $v->commission,
                        'status_name'  => $v->status_name ?: '无状态',
                        'created_at'   => $v->created_at ?: '--',
                        'updated_at'   => $v->updated_at ?: '--',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '股东ID', '股东名称', '股东手机号', '股东身份',
                  '下单用户ID', '下单用户名称', '下单用户手机号',
                  '订单ID', '订单编号',
                  '商品ID', '商品名称', '商品规格', '商品数量',
                  '分红金额', '入帐状态', '分红时间', '变动时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出区域经销商]
    public function qudaiAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $level = $this->get('level');
        $query = qudaiModel::query()->with(['member', 'qudai_last_log', 'qudai_level']);

        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if($level){
            $query = $query->where('area_level', $level);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id';
                    $query = $query->where('qudai_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('qudai_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $dataset = [];
        $query->select('*')
            ->chunk(1000, function ($qudais) use (&$dataset) {
                foreach ($qudais as $k => $v) {
                    array_push($dataset, [
                        'id'         => $v->qudai_id,
                        'nickname'   => $v->member ? $v->member->nickname : '已删除',
                        'phone'      => $v->member ? $v->member->phone : '已删除',
                        'area_name'  => $v->area_name ?: '未知',
                        'level_info' => $v->qudai_level ? $v->qudai_level->name : '未知',
                        'status'     => $v->member ? ($v->member->status == 'normal' ? '正常' : ($v->member->status == 'frozen' ? '冻结' : '锁定')) : '已删除用户',
                        'created_at' => $v->created_at ?: '--',
                        'updated_at' => ($v->qudai_last_log && $v->qudai_last_log->created_at) ? $v->qudai_last_log->created_at : '--',
                        'remark'     => $v->qudai_last_log ? $v->qudai_last_log->remark : '',
                    ]);
                }
            });
        $title = ['ID', '经销商名称', '手机号', '代理区域', '代理级别', '状态', '加入时间', '身份变动时间', '变动备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出区域经销商分红记录]
    public function qudairewardAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $query = qudairewardModel::query()->with(['qudai', 'qudaiInfo', 'buyerInfo', 'orderInfo', 'orderItemInfo', 'qudaiLevelInfo']);
        if ($mode != 'all') {
            switch ($mode) {
                case 'waiting':
                    $query = $query->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    break;
                case 'accounted':
                    $query = $query->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    break;
                case 'cancel':
                    $query = $query->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    break;
                case 'back':
                    $query = $query->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_BACK);
                    break;
            }
        }
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'qudai_id':
                    $query = $query->where('qudai_id', $keywords);
                    break;
                case 'qudai_phone':
                    $query = $query->whereIn('qudai_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'order_id':
                    $query = $query->where('order_id', $keywords);
                    break;
                case 'order_sn':
                    $query = $query->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'buyer_id':
                    $query = $query->where('buyer_id', $keywords);
                    break;
                case 'buyer_phone':
                    $query = $query->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'goods_id':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $keywords)->pluck('id')->toArray());
                    break;
                case 'goods_title':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['status_name'];
        $dataset = [];
        $query->select(['id', 'order_id', 'order_item_id', 'buyer_id', 'qudai_id', 'type', 'commission', 'area_level', 'status', 'created_at', 'updated_at'])
            ->chunk(1000, function ($qudaiRewards) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $qudaiRewards = $qudaiRewards->append($append);
                    }
                }
                foreach ($qudaiRewards as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'qudai_id'     => $v->qudai ? $v->qudai->id : '未知',
                        'qudai_name'   => $v->qudai ? $v->qudai->nickname : '未知',
                        'qudai_phone'  => $v->qudai ? $v->qudai->phone : '未知',
                        'qudai_area'   => $v->qudaiInfo ? $v->qudaiInfo->area_name : '暂无',
                        'qudai_level'  => $v->qudaiLevelInfo ? $v->qudaiLevelInfo->name : '暂无',
                        'buyer_id'     => $v->buyerInfo ? $v->buyerInfo->id : '未知',
                        'buyer_name'   => $v->buyerInfo ? $v->buyerInfo->nickname : '未知',
                        'buyer_phone'  => $v->buyerInfo ? $v->buyerInfo->phone : '未知',
                        'order_id'     => $v->orderInfo ? $v->orderInfo->id : '未知',
                        'order_sn'     => $v->orderInfo ? $v->orderInfo->order_sn : '未知',
                        'goods_id'     => $v->orderItemInfo ? $v->orderItemInfo->goods_id : '未知',
                        'goods_title'  => $v->orderItemInfo ? $v->orderItemInfo->goods_title : '未知',
                        'goods_sku'    => $v->orderItemInfo ? $v->orderItemInfo->goods_sku_text : '未知',
                        'goods_number' => $v->orderItemInfo ? $v->orderItemInfo->goods_num : '未知',
                        'commission'   => $v->commission,
                        'status_name'  => $v->status_name ?: '无状态',
                        'created_at'   => $v->created_at ?: '--',
                        'updated_at'   => $v->updated_at ?: '--',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '经销商ID', '经销商名称', '经销商手机号', '经销区域', '经销商等级',
                  '下单用户ID', '下单用户名称', '下单用户手机号',
                  '订单ID', '订单编号',
                  '商品ID', '商品名称', '商品规格', '商品数量',
                  '分红金额', '入帐状态', '分红时间', '变动时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出推客]
    public function tuikeAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $level = $this->get('level');
        $query = tuikeModel::query()->with(['member', 'tuike_last_log', 'tuike_level']);

        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if($level){
            $query = $query->where('level', $level);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id';
                    $query = $query->where('tuike_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('tuike_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $dataset = [];
        $query->select('*')
            ->chunk(1000, function ($tuikes) use (&$dataset) {
                foreach ($tuikes as $k => $v) {
                    array_push($dataset, [
                        'id'         => $v->qudai_id,
                        'nickname'   => $v->member ? $v->member->nickname : '已删除',
                        'phone'      => $v->member ? $v->member->phone : '已删除',
                        'level_info' => $v->tuike_level ? $v->tuike_level->name : '未知',
                        'status'     => $v->member ? ($v->member->status == 'normal' ? '正常' : ($v->member->status == 'frozen' ? '冻结' : '锁定')) : '已删除用户',
                        'created_at' => $v->created_at ?: '--',
                        'updated_at' => ($v->tuike_last_log && $v->tuike_last_log->created_at) ? $v->tuike_last_log->created_at : '--',
                        'remark'     => $v->tuike_last_log ? $v->tuike_last_log->remark : '',
                    ]);
                }
            });
        $title = ['ID', '推客名称', '手机号', '推客等级', '状态', '加入时间', '身份变动时间', '变动备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出推客分佣记录]
    public function tuikerewardAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $query = tuikerewardModel::query()->with(['tuike', 'buyerInfo', 'orderInfo', 'orderItemInfo', 'tuikeLevelInfo']);
        if ($mode != 'all') {
            switch ($mode) {
                case 'waiting':
                    $query = $query->where('status', tuikerewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    break;
                case 'accounted':
                    $query = $query->where('status', tuikerewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    break;
                case 'cancel':
                    $query = $query->where('status', tuikerewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    break;
                case 'back':
                    $query = $query->where('status', tuikerewardModel::COMMISSION_REWARD_STATUS_BACK);
                    break;
            }
        }
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'tuike_id':
                    $query = $query->where('tuike_id', $keywords);
                    break;
                case 'tuike_phone':
                    $query = $query->whereIn('tuike_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'order_id':
                    $query = $query->where('order_id', $keywords);
                    break;
                case 'order_sn':
                    $query = $query->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'buyer_id':
                    $query = $query->where('buyer_id', $keywords);
                    break;
                case 'buyer_phone':
                    $query = $query->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'goods_id':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $keywords)->pluck('id')->toArray());
                    break;
                case 'goods_title':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['status_name'];
        $dataset = [];
        $query->select(['id', 'order_id', 'order_item_id', 'buyer_id', 'tuike_id', 'type', 'commission', 'tuike_level', 'status', 'created_at', 'updated_at'])
            ->chunk(1000, function ($tuikerewards) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $tuikerewards = $tuikerewards->append($append);
                    }
                }
                foreach ($tuikerewards as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'tuike_id'     => $v->tuike ? $v->tuike->id : '未知',
                        'tuike_name'   => $v->tuike ? $v->tuike->nickname : '未知',
                        'tuike_phone'  => $v->tuike ? $v->tuike->phone : '未知',
                        'tuike_level'  => $v->tuikeLevelInfo ? $v->tuikeLevelInfo->name : '暂无',
                        'buyer_id'     => $v->buyerInfo ? $v->buyerInfo->id : '未知',
                        'buyer_name'   => $v->buyerInfo ? $v->buyerInfo->nickname : '未知',
                        'buyer_phone'  => $v->buyerInfo ? $v->buyerInfo->phone : '未知',
                        'order_id'     => $v->orderInfo ? $v->orderInfo->id : '未知',
                        'order_sn'     => $v->orderInfo ? $v->orderInfo->order_sn : '未知',
                        'goods_id'     => $v->orderItemInfo ? $v->orderItemInfo->goods_id : '未知',
                        'goods_title'  => $v->orderItemInfo ? $v->orderItemInfo->goods_title : '未知',
                        'goods_sku'    => $v->orderItemInfo ? $v->orderItemInfo->goods_sku_text : '未知',
                        'goods_number' => $v->orderItemInfo ? $v->orderItemInfo->goods_num : '未知',
                        'commission'   => $v->commission,
                        'status_name'  => $v->status_name ?: '无状态',
                        'created_at'   => $v->created_at ?: '--',
                        'updated_at'   => $v->updated_at ?: '--',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '推客ID', '推客名称', '推客手机号', '推客等级',
                  '下单用户ID', '下单用户名称', '下单用户手机号',
                  '订单ID', '订单编号',
                  '商品ID', '商品名称', '商品规格', '商品数量',
                  '分佣金额', '入帐状态', '分佣时间', '变动时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出推客等级变更记录]
    public function tuikelevellogsAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');

        $query = tuikelogModel::query()->with(['tuike']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'id':
                    $query = $query->where('tuike_id', $keywords);
                    break;
                case 'phone':
                    $query = $query->whereIn('tuike_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'nickname':
                    $query = $query->whereIn('tuike_id', memberModel::query()->where('nickname', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = [];
        $dataset = [];
        $query->select(['id', 'tuike_id', 'event', 'event_id', 'before', 'after', 'remark', 'oper_type', 'oper_id', 'created_at'])
            ->chunk(1000, function ($tuikelevellogs) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $tuikelevellogs = $tuikelevellogs->append($append);
                    }
                }
                foreach ($tuikelevellogs as $k => $v) {
                    array_push($dataset, [
                        'id'          => $v->id,
                        'tuike_id'    => $v->tuike ? $v->tuike->id : '未知',
                        'tuike_name'  => $v->tuike ? $v->tuike->nickname : '未知',
                        'tuike_phone' => $v->tuike ? $v->tuike->phone : '未知',
                        'event'       => $v->event ?: '--',
                        'created_at'  => $v->created_at ?: '--',
                        'before'      => $v->after ?: '0',
                        'after'       => $v->after ?: '0',
                        'remark'      => $v->remark ?: '--',
                        'oper_type'   => $v->oper_type ? $v->oper_type . ',id:' . $v->oper_id : '--',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '推客ID', '推客名称', '推客手机号', '变更类型', '变更时间', '变更前等级', '变更后等级', '变更原因', '操作人'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出推广大使]
    public function twostageAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $level = $this->get('level');
        $query = twostageModel::query()->with(['member', 'twostage_last_log', 'twostage_level']);

        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if($level){
            $query = $query->where('level', $level);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id';
                    $query = $query->where('twostage_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('twostage_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $dataset = [];
        $query->select('*')
            ->chunk(1000, function ($twostages) use (&$dataset) {
                foreach ($twostages as $k => $v) {
                    array_push($dataset, [
                        'id'         => $v->qudai_id,
                        'nickname'   => $v->member ? $v->member->nickname : '已删除',
                        'phone'      => $v->member ? $v->member->phone : '已删除',
                        'level_info' => $v->twostage_level ? $v->twostage_level->name : '未知',
                        'status'     => $v->member ? ($v->member->status == 'normal' ? '正常' : ($v->member->status == 'frozen' ? '冻结' : '锁定')) : '已删除用户',
                        'created_at' => $v->created_at ?: '--',
                        'updated_at' => ($v->twostage_last_log && $v->twostage_last_log->created_at) ? $v->twostage_last_log->created_at : '--',
                        'remark'     => $v->twostage_last_log ? $v->twostage_last_log->remark : '',
                    ]);
                }
            });
        $title = ['ID', '推广大使名称', '手机号', '推广大使等级', '状态', '加入时间', '身份变动时间', '变动备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出推广大使分佣记录]
    public function twostagerewardAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $query = twostagerewardModel::query()->with(['twostage', 'buyerInfo', 'orderInfo', 'orderItemInfo', 'twostageLevelInfo']);
        if ($mode != 'all') {
            switch ($mode) {
                case 'waiting':
                    $query = $query->where('status', twostagerewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    break;
                case 'accounted':
                    $query = $query->where('status', twostagerewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    break;
                case 'cancel':
                    $query = $query->where('status', twostagerewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    break;
                case 'back':
                    $query = $query->where('status', twostagerewardModel::COMMISSION_REWARD_STATUS_BACK);
                    break;
            }
        }
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'twostage_id':
                    $query = $query->where('twostage_id', $keywords);
                    break;
                case 'twostage_phone':
                    $query = $query->whereIn('twostage_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'order_id':
                    $query = $query->where('order_id', $keywords);
                    break;
                case 'order_sn':
                    $query = $query->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'buyer_id':
                    $query = $query->where('buyer_id', $keywords);
                    break;
                case 'buyer_phone':
                    $query = $query->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'goods_id':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $keywords)->pluck('id')->toArray());
                    break;
                case 'goods_title':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['status_name'];
        $dataset = [];
        $query->select(['id', 'order_id', 'order_item_id', 'buyer_id', 'twostage_id', 'type', 'commission', 'twostage_level', 'status', 'created_at', 'updated_at'])
            ->chunk(1000, function ($twostagerewards) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $twostagerewards = $twostagerewards->append($append);
                    }
                }
                foreach ($twostagerewards as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'twostage_id'     => $v->twostage ? $v->twostage->id : '未知',
                        'twostage_name'   => $v->twostage ? $v->twostage->nickname : '未知',
                        'twostage_phone'  => $v->twostage ? $v->twostage->phone : '未知',
                        'twostage_level'  => $v->twostageLevelInfo ? $v->twostageLevelInfo->name : '暂无',
                        'buyer_id'     => $v->buyerInfo ? $v->buyerInfo->id : '未知',
                        'buyer_name'   => $v->buyerInfo ? $v->buyerInfo->nickname : '未知',
                        'buyer_phone'  => $v->buyerInfo ? $v->buyerInfo->phone : '未知',
                        'order_id'     => $v->orderInfo ? $v->orderInfo->id : '未知',
                        'order_sn'     => $v->orderInfo ? $v->orderInfo->order_sn : '未知',
                        'goods_id'     => $v->orderItemInfo ? $v->orderItemInfo->goods_id : '未知',
                        'goods_title'  => $v->orderItemInfo ? $v->orderItemInfo->goods_title : '未知',
                        'goods_sku'    => $v->orderItemInfo ? $v->orderItemInfo->goods_sku_text : '未知',
                        'goods_number' => $v->orderItemInfo ? $v->orderItemInfo->goods_num : '未知',
                        'commission'   => $v->commission,
                        'status_name'  => $v->status_name ?: '无状态',
                        'created_at'   => $v->created_at ?: '--',
                        'updated_at'   => $v->updated_at ?: '--',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '推广大使ID', '推广大使名称', '推广大使手机号', '推广大使等级',
            '下单用户ID', '下单用户名称', '下单用户手机号',
            '订单ID', '订单编号',
            '商品ID', '商品名称', '商品规格', '商品数量',
            '分佣金额', '入帐状态', '分佣时间', '变动时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出推广大使等级变更记录]
    public function twostagelevellogsAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');

        $query = twostagelogModel::query()->with(['twostage']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'id':
                    $query = $query->where('twostage_id', $keywords);
                    break;
                case 'phone':
                    $query = $query->whereIn('twostage_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'nickname':
                    $query = $query->whereIn('twostage_id', memberModel::query()->where('nickname', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = [];
        $dataset = [];
        $query->select(['id', 'twostage_id', 'event', 'event_id', 'before', 'after', 'remark', 'oper_type', 'oper_id', 'created_at'])
            ->chunk(1000, function ($twostagelevellogs) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $twostagelevellogs = $twostagelevellogs->append($append);
                    }
                }
                foreach ($twostagelevellogs as $k => $v) {
                    array_push($dataset, [
                        'id'          => $v->id,
                        'twostage_id'    => $v->twostage ? $v->twostage->id : '未知',
                        'twostage_name'  => $v->twostage ? $v->twostage->nickname : '未知',
                        'twostage_phone' => $v->twostage ? $v->twostage->phone : '未知',
                        'event'       => $v->event ?: '--',
                        'created_at'  => $v->created_at ?: '--',
                        'before'      => $v->after ?: '0',
                        'after'       => $v->after ?: '0',
                        'remark'      => $v->remark ?: '--',
                        'oper_type'   => $v->oper_type ? $v->oper_type . ',id:' . $v->oper_id : '--',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '推广大使ID', '推广大使名称', '推广大使手机号', '变更类型', '变更时间', '变更前等级', '变更后等级', '变更原因', '操作人'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出提现记录]
    public function walletapplyAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $optionStartOn = $this->get('option_start_on');
        $optionEndOn = $this->get('option_end_on');
        $applyType = $this->get('apply_type');
        $query = \app\modules\Admin\models\memberwalletapplyModel::query()->with(['member']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($optionStartOn)) {
            $query = $query->where('updated_at', '>=', $optionStartOn);
        }
        if (!empty($optionEndOn)) {
            $query = $query->where('updated_at', '<=', $optionEndOn);
        }
        if ($mode) {
            switch ($mode) {
                case 'waiting':
                    $query = $query->where('status', 0);
                    break;
                case 'processing':
                    $query = $query->where('status', 1);
                    break;
                case 'solved':
                    $query = $query->where('status', 2);
                    break;
                case 'refuse':
                    $query = $query->where('status', -1);
                    break;
            }
        }
        if($applyType && in_array($applyType, ['bank', 'alipay', 'wechat'])){
            $query = $query->where('apply_type', $applyType);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['status_name', 'apply_type_text', 'platform_text'];
        $dataset = [];
        $query->select(['id', 'member_id', 'apply_sn', 'apply_type', 'money', 'actual_money', 'charge_money', 'service_fee', 'service_single_fee', 'status', 'platform', 'apply_info', 'remark', 'created_at', 'updated_at'])
            ->chunk(1000, function ($walletapply) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $walletapply = $walletapply->append($append);
                    }
                }
                foreach ($walletapply as $k => $v) {
                    $apply_info = !empty($v->apply_info)?json_decode($v->apply_info, true): [
                        '微信用户' => '',
                        '真实姓名' => '',
                        '开户行' => '',
                        '省' => '',
                        '市' => '',
                        '支行名称' => '',
                        '银行卡号' => '',
                        '微信ID' => '',
                        '支付宝账户' => '',
                        '身份证号' => ''
                    ];
                    if(count($apply_info)){
                        switch ($v->apply_type){
                            case 'wechat':
                                $apply_info['real_name'] = $apply_info['微信用户'];
                                $apply_info['card_no'] = $apply_info['微信ID'];
                                $apply_info['bank_name'] = '';
                                $apply_info['province'] = '';
                                $apply_info['city'] = '';
                                $apply_info['branch_name'] = '';
                                break;
                            case 'alipay':
                                $apply_info['real_name'] = $apply_info['真实姓名'];
                                $apply_info['card_no'] = $apply_info['支付宝账户'];
                                $apply_info['bank_name'] = '';
                                $apply_info['province'] = '';
                                $apply_info['city'] = '';
                                $apply_info['branch_name'] = '';
                                break;
                            default:
                                $apply_info['real_name'] = $apply_info['真实姓名'];
                                $apply_info['card_no'] = $apply_info['银行卡号'];
                                $apply_info['bank_name'] = $apply_info['开户行'];
                                $apply_info['province'] = $apply_info['省'];
                                $apply_info['city'] = $apply_info['市'];
                                $apply_info['branch_name'] = $apply_info['支行名称'];
                        }
                        $apply_info['identity_card_number'] = $apply_info['身份证号码'];
                    }
                    array_push($dataset, [
                        'id'               => $v->id,
                        'user_id'          => $v->member ? $v->member->id : '未知',
                        'user_name'        => $v->member ? $v->member->nickname : '未知',
                        'user_phone'       => $v->member ? $v->member->phone : '未知',
                        'money'            => $v->money ?: '0',
                        'actual_money'     => $v->actual_money ?: '0',
                        'charge_money'     => $v->charge_money ?: '0',
                        'service_fee'      => $v->service_fee ? ($v->service_fee * 100) . '%' : '0',
                        'service_single_fee' => $v->service_single_fee,
                        'payable_money'    => bcsub(bcsub($v->money, $v->charge_money, 2), $v->service_single_fee, 2),
                        'apply_type_text'  => $v->apply_type_text ?: '--',
                        'apply_info_real_name'  => $apply_info['real_name'],
                        'apply_info_bank_name'  => $apply_info['bank_name'],
                        'apply_info_province'  => $apply_info['province'],
                        'apply_info_city'  => $apply_info['city'],
                        'apply_info_branch_name'  => $apply_info['branch_name'],
                        'apply_info_card_no'  => $apply_info['card_no'],
                        'identity_card_number'  => $apply_info['identity_card_number'],
                        'created_at'       => $v->created_at ?: '--',
                        'status_name'      => $v->status_name ?: '--',
                        'updated_at'       => $v->updated_at ?: '--',
                        'remark'           => $v->remark ?: '无',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '申请用户ID', '申请用户名称', '申请用户手机号', '提现金额', '实际到帐金额', '手续费', '手续费费率', '单笔手续费', '应付金额', '提现方式', '真实姓名', '开户行', '省', '市', '支行名称', '银行卡号', '身份证号码', '申请时间', '申请状态', '操作时间', '原因/备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出充值记录]
    public function walletrechargeAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');

        $query = \app\modules\Admin\models\memberwalletrechargeModel::query()->with(['getMember']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if ($mode) {
            switch ($mode) {
                case 'success':
                    $query = $query->where('status', 1);
                    break;
                case 'waiting':
                    $query = $query->where('status', 0);
                    break;
            }
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['payment_text', 'status_text'];
        $dataset = [];

        $query->select(['id', 'member_id', 'money', 'before', 'after', 'status', 'payment', 'created_at'])
            ->chunk(1000, function ($walletrecharge) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $walletrecharge = $walletrecharge->append($append);
                    }
                }
                foreach ($walletrecharge as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'user_id'      => $v->getMember ? $v->getMember->id : '未知',
                        'user_name'    => $v->getMember ? $v->getMember->nickname : '未知',
                        'user_phone'   => $v->getMember ? $v->getMember->phone : '未知',
                        'money'        => $v->money ?: '0',
                        'before'       => $v->before ?: '0',
                        'after'        => $v->after ?: '0',
                        'payment_text' => $v->payment_text ?: '--',
                        'status_text'  => $v->status_text ?: '--',
                        'created_at'   => $v->created_at ?: '--',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '用户ID', '用户名称', '用户手机号', '充值金额', '充值前金额', '充值后金额', '支付方式', '充值状态', '充值时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出转帐记录]
    public function wallettransferAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');

        $query = \app\modules\Admin\models\membertransferlogModel::query()->with(['getMember', 'getTarget']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if ($mode) {
            switch ($mode) {
                case 'money':
                    $query = $query->where('wallet_type', 'money');
                    break;
                case 'score':
                    $query = $query->where('wallet_type', 'score');
                    break;
            }
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'target_id':
                    $query = $query->where('target_id', $keywords);
                    break;
                case 'target_phone':
                    $query = $query->whereIn('target_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['wallet_type_name', 'type_text'];
        $dataset = [];
        $query->select(['id', 'member_id', 'target_id', 'wallet', 'wallet_type', 'remark', 'created_at'])
            ->chunk(1000, function ($wallettransfer) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $wallettransfer = $wallettransfer->append($append);
                    }
                }
                foreach ($wallettransfer as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'user_id'      => $v->getMember ? $v->getMember->id : '未知',
                        'user_name'    => $v->getMember ? $v->getMember->nickname : '未知',
                        'user_phone'   => $v->getMember ? $v->getMember->phone : '未知',
                        'target_id'      => $v->getTarget ? $v->getTarget->id : '未知',
                        'target_name'    => $v->getTarget ? $v->getTarget->nickname : '未知',
                        'target_phone'   => $v->getTarget ? $v->getTarget->phone : '未知',
                        'wallet_type_name'   => $v->wallet_type_name ?: '未知',
                        'wallet'        => $v->wallet ?: '0',
                        'created_at'   => $v->created_at ?: '--',
                        'remark'       => $v->remark ?: '无',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '转出用户ID', '转出用户名称', '转出用户手机号', '转入用户ID', '转入用户名称', '转入用户手机号', '转账类型', '转帐金额/积分', '转账时间', '转账备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出余额变动明细记录]
    public function moneylogsAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');

        $query = \app\modules\Admin\models\membermoneylogModel::query()->with(['getMember']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($mode) && $mode != 'all') {
            $query = $query->where('event', $mode);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['event_text'];
        $dataset = [];

        $query->select(['id', 'member_id', 'event', 'before', 'money', 'after', 'remark', 'created_at'])
            ->chunk(1000, function ($moneylogs) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $moneylogs = $moneylogs->append($append);
                    }
                }
                foreach ($moneylogs as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'user_id'      => $v->getMember ? $v->getMember->id : '未知',
                        'user_name'    => $v->getMember ? $v->getMember->nickname : '未知',
                        'user_phone'   => $v->getMember ? $v->getMember->phone : '未知',
                        'event_text'   => $v->event_text ?: '未知',
                        'money'        => $v->money ?: '0',
                        'before'        => $v->before ?: '0',
                        'after'        => $v->after ?: '0',
                        'created_at'   => $v->created_at ?: '--',
                        'remark'       => $v->remark ?: '无',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '用户ID', '用户名称', '用户手机号', '变动类型', '变动金额', '变动前金额', '变动后金额', '变动时间', '备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出积分变动明细记录]
    public function scorelogsAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');

        $query = \app\modules\Admin\models\memberscorelogModel::query()->with(['getMember']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($mode) && $mode != 'all') {
            $query = $query->where('event', $mode);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['event_text'];
        $dataset = [];

        $query->select(['id', 'member_id', 'event', 'before', 'score', 'after', 'remark', 'created_at'])
            ->chunk(1000, function ($moneylogs) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $moneylogs = $moneylogs->append($append);
                    }
                }
                foreach ($moneylogs as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'user_id'      => $v->getMember ? $v->getMember->id : '未知',
                        'user_name'    => $v->getMember ? $v->getMember->nickname : '未知',
                        'user_phone'   => $v->getMember ? $v->getMember->phone : '未知',
                        'event_text'   => $v->event_text ?: '未知',
                        'score'        => $v->score ?: '0',
                        'before'        => $v->before ?: '0',
                        'after'        => $v->after ?: '0',
                        'created_at'   => $v->created_at ?: '--',
                        'remark'       => $v->remark ?: '无',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '用户ID', '用户名称', '用户手机号', '变动类型', '变动积分', '变动前积分', '变动后积分', '变动时间', '备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出平台收益记录]
    public function platformprofitAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');

        $query = \app\modules\Admin\models\orderModel::query()->with([
            'orderItems' => function (\Illuminate\Database\Eloquent\Relations\HasMany $query) {
                $query->where('refund_status', '<', 1);
				$query->where('aftersale_status', '<', 1);
                $query->select(['id', 'order_id', 'goods_id', 'goods_title', 'goods_image', 'goods_price', 'pay_price', 'cost_price', 'goods_num', 'goods_sku_text']);
                $query->withSum('gudongfenhong', 'commission');
                $query->withSum('qudaireward', 'commission');
                $query->withSum('tuikereward', 'commission');
                $query->withSum('agentreward', 'commission');
            }
        ])->select(['id', 'order_sn', 'pay_type', 'pay_fee', 'paytime', 'created_at']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($mode)) {
            switch ($mode){
                case 'paid':
                    $query = $query->where('status', 1);
                    break;
                case 'finished':
                    $query = $query->where('status', 2);
                    break;
                default:
                    $query = $query->where('status', '>',0);
            }
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'order_id':
                    $query = $query->where('id', $keywords);
                    break;
                case 'order_sn':
                    if(mb_strlen($keywords, 'utf-8') < 4){
                        $query = $query->where('id', 0);
                    }else{
                        $query = $query->where('order_sn', 'like', "%{$keywords}%");
                    }
                    break;
                case 'user_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'customer_id':
                    $query = $query->where('customer_id', $keywords);
                    break;
                case 'goods_id':
                    $query = $query->whereIn('id', \app\modules\Admin\models\orderItemModel::query()->where('goods_id', $keywords)->pluck('order_id')->toArray());
                    break;
                case 'goods_name':
                    $query = $query->whereIn('id', \app\modules\Admin\models\orderItemModel::query()->where('goods_title', 'like', "%{$keywords}%")->pluck('order_id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');

        $dataset = [];

        $query->select(['*'])
            ->chunk(1000, function ($platformprofits) use (&$dataset) {
                foreach ($platformprofits as $k => $v) {
                    switch ($v->pay_type) {
                        case 'wechat':
                            $v->pay_type_text = '微信支付';
                            break;
                        case 'alipay':
                            $v->pay_type_text =  '支付宝';
                            break;
                        case 'wallet':
                            $v->pay_type_text =  '钱包支付';
                            break;
                        case 'score':
                            $v->pay_type_text =  '积分支付';
                            break;
                        case 'pickgoods':
                            $v->pay_type_text =  '提货卡';
                            break;
                        default:
                            $v->pay_type_text =  '三方支付';
                    }
                    foreach ($v->orderItems as $item){
                        if(empty($item->gudongfenhong_sum_commission)){
                            $item->gudongfenhong_sum_commission = 0.00;
                        }
                        if(empty($item->qudaireward_sum_commission)){
                            $item->qudaireward_sum_commission = 0.00;
                        }
                        if(empty($item->tuikereward_sum_commission)){
                            $item->tuikereward_sum_commission = 0.00;
                        }
                        if(empty($item->agentreward_sum_commission)){
                            $item->agentreward_sum_commission = 0.00;
                        }
                        if(empty($item->cost_price)){
                            $item->cost_price = 0.00;
                        }
                        if(empty($item->pay_price)){
                            $item->pay_price = 0.00;
                        }
                        $item->cost_price = $item->cost_price * $item->goods_num;
                        $platform_profit = bcsub($item->pay_price, $item->cost_price, 3);
                        $platform_profit = bcsub($platform_profit, $item->agentreward_sum_commission, 3);
                        $platform_profit = bcsub($platform_profit, $item->gudongfenhong_sum_commission, 3);
                        $platform_profit = bcsub($platform_profit, $item->qudaireward_sum_commission, 3);
                        $platform_profit = bcsub($platform_profit, $item->tuikereward_sum_commission, 3);
                        $item->platform_profit = round($platform_profit ,2);
                        array_push($dataset, [
                            'id'                           => $v->id,
                            'order_sn'                     => $v->order_sn,
                            'created_at'                   => $v->created_at,
                            'pay_fee'                      => $v->pay_fee,
                            'pay_type_text'                => $v->pay_type_text,
                            'paytime_text'                 => $v->paytime_text,
                            'goods_id'                     => $item->goods_id,
                            'goods_title'                  => $item->goods_title,
                            'goods_sku_text'               => $item->goods_sku_text,
                            'goods_price'                  => $item->goods_price,
                            'goods_num'                    => $item->goods_num,
                            'pay_price'                    => $item->pay_price,
                            'cost_price'                   => $item->cost_price,
                            'agentreward_sum_commission'   => $item->agentreward_sum_commission,
                            'gudongfenhong_sum_commission' => $item->gudongfenhong_sum_commission,
                            'qudaireward_sum_commission'   => $item->qudaireward_sum_commission,
                            'tuikereward_sum_commission'   => $item->tuikereward_sum_commission,
                            'platform_profit'              => $item->platform_profit,
                        ]);
                    }
                    unset($item);
                }
                unset($k);
                unset($v);
            });
        $title = ['订单ID', '订单编号', '下单时间', '支付金额', '支付方式', '支付时间', '商品ID', '商品名称', '商品规格', '商品单价', '商品数量', '实付金额', '成本价', '代理分红', '股东分红', '区域经销商分红', '推客分佣', '平台利润'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出个人消费明细]
    public function agentTotalConsumeAction()
    {
        $id = $this->get('id');
        $keywordsType = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('startOn');
        $endOn = $this->get('endOn');
        $path = $this->get('path');

        $query = (new \orderModel)->withTrashed()->with('member')->where('status', '>', 0);
        $query = $query->where(function ($query) use ($id) {
            $query->where('customer_id', $id)->orWhere(function ($query) use ($id) {
                $query->where('member_id', $id)->where('customer_id', 0);
            });
        })->whereExists(function ($query) {
            $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                ->where('calc_consume', '=', 1)
                ->where('refund_status', '<', 2);
        });

        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if ($keywords !== '') {
            switch ($keywordsType) {
                case 'order_id':
                    $query = $query->where('id', $keywords);
                    break;
                case 'order_sn':
                    $query = $query->where('order_sn', 'like', "%{$keywords}%");
                    break;
                case 'member_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'member_phone':
                    $query = $query->whereIn('member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                    break;
                case 'customer_id':
                    $query = $query->where('customer_id', $keywords);
                    break;
                case 'consignee':
                    $query = $query->where('consignee', $keywords);
                    break;
                case 'consignee_phone':
                    $query = $query->where('phone', 'like', "%{$keywords}%");
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');

        $dataset = [];

        $query->select(['*'])
            ->chunk(1000, function ($totalConsumeLists) use (&$dataset) {
                foreach ($totalConsumeLists as $k => $v) {
                    array_push($dataset, [
                        'id'                           => $v->id,
                        'order_sn'                     => $v->order_sn,
                        'member_id'                    => $v->member?$v->member->id:'---',
                        'member_nickname'              => $v->member?($v->member->nickname.($v->member->realname?'('.$v->member->realname.')':'')):'---',
                        'member_phone'                 => ($v->member&&$v->member->phone)?$v->member->phone:'---',
                        'consignee'                    => $v->consignee?:'---',
                        'consignee_phone'              => $v->phone?:'---',
                        'consignee_address'            => ($v->province_name?:'').($v->city_name?:'').($v->area_name?:'').($v->address?:'---'),
                        'status_name'                  => $v->status_name,
                        'total_amount'                 => $v->total_amount,
                        'total_fee'                    => $v->total_fee,
                        'discount_fee'                 => $v->discount_fee,
                        'pay_type_text'                => $v->pay_type_text,
                        'paytime'                      => timestamp($v->paytime),
                        'memo'                         => $v->memo?:'',
                        'remark'                       => $v->remark?:'',
                        'created_at'                   => $v->created_at,
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['订单ID','订单编号','下单用户ID','下单用户昵称(姓名)','下单用户电话',
            '收货人','收货人电话','收货人地址','订单状态','订单总金额','支付金额','折扣总金额','支付方式','支付时间',
            '商户备注','用户备注','下单时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出团队业绩明细]
    public function agentTeamConsumeAction()
    {
        $id = $this->get('id');
        $keywordsType = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('startOn');
        $endOn = $this->get('endOn');
        $mode = $this->get('mode');
        $path = $this->get('path');

        $query    = (new \orderModel)->withTrashed()
            ->join('order_item', 'order.id', '=', 'order_item.order_id')
            ->with('member')
            ->where('order.status', '>', 0)
            ->where('order_item.calc_consume', '=', 1)
            ->whereRaw("(cs_order_item.member_id={$id} OR cs_order_item.member_id in (SELECT children_id from cs_member_children where `member_id`={$id}))");
        if( $mode =='included' ) {
            $query =  $query->where('refund_status', '<', 2);
        } else {
            $query =  $query->where('refund_status', '>=', 2);
        }
        if (!empty($startOn)) {
            $query = $query->where('order.created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('order.created_at', '<=', $endOn);
        }
        if ($keywords !== '') {
            switch ($keywordsType) {
                case 'order_id':
                    $query = $query->where('order.id', $keywords);
                    break;
                case 'order_sn':
                    $query = $query->where('order.order_sn', 'like', "%{$keywords}%");
                    break;
                case 'member_id':
                    $query = $query->where('order_item.member_id', $keywords);
                    break;
                case 'member_phone':
                    $query = $query->whereIn('order_item.member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                    break;
                case 'consignee':
                    $query = $query->where('order.consignee', $keywords);
                    break;
                case 'consignee_phone':
                    $query = $query->where('order.phone', 'like', "%{$keywords}%");
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');

        $dataset = [];
        $query->select(
            'order.id', 'order_item.id as item_id', 'order.order_sn', 'order.consignee', 'order.address', 'order.phone', 'order.province_name', 'order.city_name', 'order.area_name', 'order.status',
            'order.pay_type', 'order.paytime', 'order.memo', 'order.remark', 'order.created_at',
            'order_item.pay_price', 'order_item.member_id', 'order_item.discount_fee'
        )->chunk(1000, function ($totalConsumeLists) use (&$dataset) {
                foreach ($totalConsumeLists as $k => $v) {
                    array_push($dataset, [
                        'id'                           => $v->item_id,
                        'order_sn'                     => $v->order_sn,
                        'member_id'                    => $v->member?$v->member->id:'---',
                        'member_nickname'              => $v->member?($v->member->nickname.($v->member->realname?'('.$v->member->realname.')':'')):'---',
                        'member_phone'                 => ($v->member&&$v->member->phone)?$v->member->phone:'---',
                        'consignee'                    => $v->consignee?:'---',
                        'consignee_phone'              => $v->phone?:'---',
                        'consignee_address'            => ($v->province_name?:'').($v->city_name?:'').($v->area_name?:'').($v->address?:'---'),
                        'status_name'                  => $v->status_name,
                        'pay_price'                    => $v->pay_price,
                        'pay_type_text'                => $v->pay_type_text,
                        'paytime'                      => timestamp($v->paytime),
                        'memo'                         => $v->memo?:'',
                        'remark'                       => $v->remark?:'',
                        'created_at'                   => $v->created_at,
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['订单货品ID','订单编号','下单用户ID','下单用户昵称(姓名)','下单用户电话',
            '收货人','收货人电话','收货人地址','订单状态','订单金额','支付方式','支付时间',
            '商户备注','用户备注','下单时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出直推业绩明细]
    public function agentTeamConsumeV1Action()
    {
        $id = $this->get('id');
        $keywordsType = $this->get('type');
        $keywords = $this->get('keywords');
        $startOn = $this->get('startOn');
        $endOn = $this->get('endOn');
        $mode = $this->get('mode');
        $path = $this->get('path');

        $query    = (new \orderModel)->withTrashed()
            ->join('order_item', 'order.id', '=', 'order_item.order_id')
            ->with('member')
            ->where('order.status', '>', 0)
            ->where('order_item.calc_consume', '=', 1)
            ->whereRaw("cs_order_item.member_id in (SELECT children_id from cs_member_children where `level`=1 and `member_id`={$id})");

        if( $mode =='included' ) {
            $query =  $query->where('refund_status', '<', 2);
        } else {
            $query =  $query->where('refund_status', '>=', 2);
        }
        if (!empty($startOn)) {
            $query = $query->where('order.created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('order.created_at', '<=', $endOn);
        }
        if ($keywords !== '') {
            switch ($keywordsType) {
                case 'order_id':
                    $query = $query->where('id', $keywords);
                    break;
                case 'order_sn':
                    $query = $query->where('order_sn', 'like', "%{$keywords}%");
                    break;
                case 'member_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'member_phone':
                    $query = $query->whereIn('member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                    break;
                case 'customer_id':
                    $query = $query->where('customer_id', $keywords);
                    break;
                case 'consignee':
                    $query = $query->where('consignee', $keywords);
                    break;
                case 'consignee_phone':
                    $query = $query->where('phone', 'like', "%{$keywords}%");
                    break;
            }
        }
        $query = $query->orderBy('order.created_at', 'desc');

        $dataset = [];

        $query->select(
            'order.id', 'order_item.id as item_id', 'order.order_sn', 'order.consignee', 'order.address', 'order.phone', 'order.province_name', 'order.city_name', 'order.area_name', 'order.status',
            'order.pay_type', 'order.paytime', 'order.memo', 'order.remark', 'order.created_at',
            'order_item.pay_price', 'order_item.member_id', 'order_item.discount_fee'
        )->chunk(1000, function ($totalConsumeLists) use (&$dataset) {
                foreach ($totalConsumeLists as $k => $v) {
                    array_push($dataset, [
                        'id'                           => $v->item_id,
                        'order_sn'                     => $v->order_sn,
                        'member_id'                    => $v->member?$v->member->id:'---',
                        'member_nickname'              => $v->member?($v->member->nickname.($v->member->realname?'('.$v->member->realname.')':'')):'---',
                        'member_phone'                 => ($v->member&&$v->member->phone)?$v->member->phone:'---',
                        'consignee'                    => $v->consignee?:'---',
                        'consignee_phone'              => $v->phone?:'---',
                        'consignee_address'            => ($v->province_name?:'').($v->city_name?:'').($v->area_name?:'').($v->address?:'---'),
                        'status_name'                  => $v->status_name,
                        'pay_price'                    => $v->pay_price,
                        'pay_type_text'                => $v->pay_type_text,
                        'paytime'                      => timestamp($v->paytime),
                        'memo'                         => $v->memo?:'',
                        'remark'                       => $v->remark?:'',
                        'created_at'                   => $v->created_at,
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['订单货品ID','订单编号','下单用户ID','下单用户昵称(姓名)','下单用户电话',
            '收货人','收货人电话','收货人地址','订单状态','支付金额','支付方式','支付时间',
            '商户备注','用户备注','下单时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出用户转帐统计]
    public function wallettransferstatisticsAction()
    {
        $type = $this->get('type');
        $roll_type = $this->get('roll_type');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $mode = $this->get('mode');
        $path = $this->get('path');
        
        $rollType = \app\modules\Admin\models\membertransferlogModel::getRollType();
        $walletType = array_merge(['all' => '全部'], \app\modules\Admin\models\membertransferlogModel::getWalletType());
        $modeArray = [
            'all' => '全部',
            'today' => '今天',
            'yesterday' => '昨天',
            'thisweek' => '本周',
            'lastweek' => '上周',
            'thismonth' => '本月',
            'lastmonth' => '上月',
            'other' => '自定义'
        ];
        $actionArray = array_keys($rollType);
        if(!in_array($roll_type, $actionArray)){
            $roll_type = 'rollout';
        }
        $groupByArray = ['member_id'];
        if($roll_type === 'rollout'){
            $query = \app\modules\Admin\models\membertransferlogModel::query()
                ->with(['getMember'=>function($withQuery){
                    $withQuery->withTrashed();
                }])
                ->select(['id','member_id','wallet','wallet_type']);
        }else{
            $query = \app\modules\Admin\models\membertransferlogModel::query()
                ->with(['getTarget'=>function($withQuery){
                    $withQuery->withTrashed();
                }])
                ->select(['id','target_id','wallet','wallet_type']);
            $groupByArray = ['target_id'];
        }
        $query = $query->addSelect(DB::Raw("SUM(wallet) as total_trans"))
            ->addSelect(DB::Raw("COUNT(id) as trans_num"));
        $WalletTypeArray = array_keys($walletType);
        $type = in_array($type, $WalletTypeArray)?$type:$WalletTypeArray[0];
        if($type !== 'all'){
            $query = $query->where('wallet_type', '=', $type);
        }else{
            array_unshift($groupByArray, 'wallet_type');
        }
        if(count($groupByArray)){
            $query = $query->groupBy($groupByArray);
        }
        $mode_array = array_keys($modeArray);
        $mode = in_array($mode, $mode_array)?$mode:'all';
        $startOnN = '';
        $endOnN = '';
        $operator = 'between';
        switch ($mode){
            case 'today':
                $startOnN = carbon()->today()->format('Y-m-d');
                $operator = 'eq';
                break;
            case 'thisweek':
                $startOnN = carbon()->startOfWeek()->format('Y-m-d');
                break;
            case 'yesterday':
                $startOnN = carbon()->yesterday()->format('Y-m-d');
                $operator = 'eq';
                break;
            case 'lastweek':
                $startOnN = carbon()->subDays(7)->startOfWeek()->format('Y-m-d');
                $endOnN = carbon()->subDays(7)->endOfWeek()->format('Y-m-d');
                break;
            case 'thismonth':
                $startOnN = carbon()->startOfMonth()->format('Y-m-d');
                break;
            case 'lastmonth':
                $startOnN = carbon()->subMonth()->startOfMonth()->format('Y-m-d');
                $endOnN =  carbon()->subMonth()->endOfMonth()->format('Y-m-d');
                break;
            case 'other':
                if(!empty($startOn)){
                    $startOnN = $startOn;
                }
                if(!empty($endOn)){
                    $endOnN = $endOn;
                }
                break;
        }
        if(!empty($startOnN)){
            if($operator === 'between'){
                $query = $query->where('created_at', '>=', $startOnN);
            }else{
                $query = $query->where('created_at', '=', $startOnN);
            }
        }
        if(!empty($endOnN)){
            $query = $query->where('created_at', '<=', $endOnN);
        }
        $query = $query->orderBy('total_trans', 'desc');

        $dataset = [];

        $query->chunk(1000, function ($transferStatisticsLists) use (&$dataset, $roll_type) {
                foreach ($transferStatisticsLists as $k => $v) {
                    if($roll_type === 'rollout'){
                        $newRow = [
                            'user_id'                           => $v->member_id,
                            'user_nickname'              => $v->getMember?($v->getMember->nickname.($v->getMember->realname?'('.$v->getMember->realname.')':'')):'---',
                            'user_phone'                 => ($v->getMember&&$v->getMember->phone)?$v->getMember->phone:'---',
                            'wallet_type_name'                    => $v->wallet_type_name?:'---',
                            'total_trans'              => $v->total_trans?:'---',
                            'trans_num'              => $v->trans_num?:'---',
                        ];
                    }else{
                        $newRow = [
                            'user_id'                           => $v->target_id,
                            'user_nickname'              => $v->getTarget?($v->getTarget->nickname.($v->getTarget->realname?'('.$v->getTarget->realname.')':'')):'---',
                            'user_phone'                 => ($v->getTarget&&$v->getTarget->phone)?$v->getTarget->phone:'---',
                            'wallet_type_name'                    => $v->wallet_type_name?:'---',
                            'total_trans'              => $v->total_trans?:'---',
                            'trans_num'              => $v->trans_num?:'---',
                        ];
                    }
                    array_push($dataset, $newRow);
                }
                unset($k);
                unset($v);
            });
        if($roll_type === 'rollout'){
            $title = ['转出用户ID','转出用户昵称','转出用户手机号', '转出类型','转出总额','转出次数'];
        }else{
            $title = ['转入用户ID','转入用户昵称','转入用户手机号', '转入类型','转入总额','转入次数'];
        }
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出用户销量统计]
    public function rankinglistAction()
    {
        $mode = $this->get('mode');
        $qudai = $this->get('qudai');
        $tuike = $this->get('tuike');
        $gudong = $this->get('gudong');
        $agent = $this->get('agent');
        $path = $this->get('path');

        $modeArray = [
            'today',
            'thisweek',
            'yesterday',
            'lastweek',
            'thismonth',
            'lastmonth'
        ];
        if(!in_array($mode, $modeArray)){
            $mode = $modeArray[0];
        }
        $query = \app\modules\Admin\models\rankinglistModel::query()->with([
            'member' =>function ($withQuery){
                $withQuery->select(['id', 'phone', 'nickname', 'realname', 'avatar', 'status']);
            },
            'agent'=>function($withQuery){
                $withQuery->select('id', 'level');
            },
            'gudong',
            'tuike'=>function($withQuery){
                $withQuery->with('tuike_level')->select('tuike_id', 'level');
            },
            'qudai'=>function($withQuery){
                $withQuery->with('qudai_level')->select('qudai_id', 'area_level', 'area', 'area_name');
            }
        ]);
        $query = $query->where('mode', '=', $mode);
        if(is_numeric($agent) && $agent > 0){
            $query = $query->whereHas('agent', function ($hasWhere) use($agent){
                $hasWhere->where('member.level', $agent);
            });
        }
        if(is_numeric($gudong) && $gudong > 0){
            $query = $query->whereHas('gudong')->whereHas('member', function ($hasWhere) use($gudong){
                $hasWhere->where('member.level', $gudong);
            });
        }
        if(is_numeric($tuike) && $tuike > 0){
            $query = $query->whereHas('tuike', function ($hasWhere) use($tuike){
                $hasWhere->where('tuike.level', $tuike);
            });
        }
        if(is_numeric($qudai) && $qudai > 0){
            $query = $query->whereHas('qudai', function ($hasWhere) use($qudai){
                $hasWhere->where('qudai.area_level', $qudai);
            });
        }
        $query = $query->orderBy('consume', 'desc');

        $dataset = [];

        $query->chunk(1000, function ($rankingDataLists) use (&$dataset) {
            foreach ($rankingDataLists as $k => $v) {
                $newRow = [
                    'user_id' => $v->member_id
                ];
                $user_name = '---';
                if($v->member){
                    if($v->member->nickname){
                        $user_name = $v->member->nickname;
                    }else{
                        $user_name = $v->member_id;
                    }
                    if($v->member->realname){
                        $user_name .= '('.$v->member->realname.')';
                    }
                }
                $newRow['user_nickname'] = $user_name;
                $user_phone = '---';
                if($v->member){
                    if($v->member->phone){
                        $user_phone = $v->member->phone;
                    }
                }
                $newRow['user_phone'] = $user_phone;
                $agent = '---';
                if($v->agent){
                    if($v->agent->level_info&&$v->agent->level_info->name){
                        $agent = $v->agent->level_info->name;
                    }else{
                        $agent = $v->agent->level;
                    }
                }
                $newRow['agent'] = $agent;
                $gudong = '---';
                if($v->gudong){
                    if($v->agent){
                        if($v->agent->level_info&&$v->agent->level_info->name){
                            $gudong =  $v->agent->level_info->name;
                        }else{
                            $gudong =  $v->agent->level;
                        }
                    }
                }
                $newRow['gudong'] = $gudong;
                $tuike = '---';
                if($v->tuike){
                    if($v->tuike->tuike_level&&$v->tuike->tuike_level->name){
                        $tuike =  $v->tuike->tuike_level->name;
                    }else{
                        $tuike =  $v->tuike->level;
                    }
                }
                $newRow['tuike'] = $tuike;
                $qudai = '---';
                if($v->qudai){
                    if($v->qudai->qudai_level&&$v->qudai->qudai_level->name){
                        $qudai_name = $v->qudai->qudai_level->name;
                        if($v->qudai->area_name){
                            $qudai_name .= '('.$v->qudai->area_name.')';
                        }
                        $qudai =  $qudai_name;
                    }else{
                        $qudai_name = $v->qudai->area_level;
                        if($v->qudai->area_name){
                            $qudai_name .= '('.$v->qudai->area_name.')';
                        }
                        $qudai =  $qudai_name;
                    }
                }
                $newRow['qudai'] = $qudai;
                $newRow['consume'] = $v->consume?:'---';
                $newRow['order_num'] = $v->order_num?:'---';
                $newRow['created_at'] = $v->created_at->format('Y-m-d H:i:s')?:'---';
                array_push($dataset, $newRow);
                unset($user_name, $user_phone, $qudai, $gudong, $agent, $tuike, $qudai_name, $newRow);
            }
            unset($k, $v);
        });
        $title = ['用户ID','用户昵称','用户手机号', '代理身份','股东身份','推客身份','区域经销商身份','销售业绩总额', '订单总数', '统计时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出用户销售业绩订单列表]
    public function rankingmemberorderlistAction()
    {
        $id = $this->get('id',0);
        $start_on     = $this->get('start_on', '');
        $end_on       = $this->get('end_on', '');
        $keywordsType = $this->get('type', '');
        $keywords     = $this->get('keywords', '');
        $path = $this->get('path');
        $dataset = [];
        $order_ids = \app\modules\Admin\models\rankinglistModel::query()->where('id', $id)->value('order_ids');
        if(!empty($order_ids)){
            $query = (new orderModel)->withTrashed()->with('member')->whereIn('id', explode(',',$order_ids));
            if (!empty($start_on)) {
                $query = $query->where('created_at', '>=', $start_on);
            }
            if (!empty($end_on)) {
                $query = $query->where('created_at', '<=', $end_on);
            }
            if ($keywords !== '') {
                switch ($keywordsType) {
                    case 'order_id':
                        $query = $query->where('id', $keywords);
                        break;
                    case 'order_sn':
                        $query = $query->where('order_sn', 'like', "%{$keywords}%");
                        break;
                    case 'consignee':
                        $query = $query->where('consignee', $keywords);
                        break;
                    case 'consignee_phone':
                        $query = $query->where('phone', 'like', "%{$keywords}%");
                        break;
                }
            }
            $query->orderByDesc('created_at')
            ->chunk(1000, function ($rankingmemberorderLists) use (&$dataset) {
                $rankingmemberorderLists = $rankingmemberorderLists->append('status_name');
                foreach ($rankingmemberorderLists as $k => $v) {
                    $consignee_address = $v->province_name?:'';
                    $consignee_address .= $v->city_name?:'';
                    $consignee_address .= $v->area_name?:'';
                    $consignee_address .= $v->address?:'';
                    $new_row = [
                        'order_id' => $v->id,
                        'order_sn' => $v->order_sn,
                        'member_id' => $v->member_id,
                        'member_name' => ($v->member&&$v->member->nickname)?$v->member->nickname:'',
                        'member_phone' => ($v->member&&$v->member->phone)?$v->member->phone:'',
                        'consignee' => $v->consignee,
                        'consignee_phone' => $v->phone,
                        'consignee_address' => $consignee_address,
                        'status_name' => $v->status_name,
                        'total_amount' => $v->total_amount,
                        'total_fee'=>$v->total_fee,
                        'discount_fee'=>$v->discount_fee,
                        'pay_type_text'=>$v->pay_type_text,
                        'paytime'=>timestamp($v->paytime),
                        'memo'=>$v->memo,
                        'remark'=>$v->remark,
                        'created_at'=>$v->created_at
                    ];
                    array_push($dataset, $new_row);
                    unset($new_row, $consignee_address);
                }
                unset($k, $v);
            });
        }
        $title = ['订单ID', '订单编号', '下单用户ID','下单用户昵称','下单用户手机号', '收货人','收货人电话','收货地址','订单状态','订单总金额', '支付金额', '折扣总金额'
                  ,'支付方式','支付时间', '商户备注', '用户备注', '下单时间'
        ];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出代理团队列表]
    public function agentTeamListAction()
    {
        $id = $this->get('id',0);
        $agent_level     = $this->get('agent_level', '');
        $level       = $this->get('level', '');
        $keywordsType = $this->get('type', '');
        $keywords     = $this->get('keywords', '');

        $path = $this->get('path');

        $query = (new memberModel)->withTrashed()->join('member_children', 'member.id', '=', 'member_children.children_id')
                                  ->where('member_children.member_id', $id)
                                  ->whereNull('member.deleted_at');
        if($level>0){
            $query = $query->where('member_children.level', $level);
        }
        if($agent_level>0){
            $query = $query->where('member.level', $agent_level);
        }
        $type     = $this->get('keywordsType');
        $keywords = $this->get('keywords');
        if ($keywords) {
            $query = $query->where('member.'.$type, $keywords);
        }
        $query = $query->select('member.*');

        $dataset = [];
        $query->orderByDesc('created_at')
              ->chunk(1000, function ($agentTeamLists) use (&$dataset) {
                  foreach ($agentTeamLists as $k => $v) {
                      $child_user_count = DB::table('member_children')->where('member_id', $v->id)->where('children_deleted', 0)->count();
                      $status_test         = match ($v->status) {
                          'normal' => '正常',
                          'frozen' => '冻结',
                          'lock' => '锁定',
                          default => '未知',
                      };
                      $new_row = [
                          'id' => $v->id,
                          'nickname' => $v->nickname,
                          'parent_member_id' => $v->parent_member_id,
                          'phone' => $v->phone?:'',
                          'level_info' => ($v->level_info&&$v->level_info->name)?$v->level_info->name:'普通会员',
                          'money' => $v->money,
                          'score' => $v->score,
                          'total_income' => $v->total_income,
                          'total_consume' => $v->total_consume,
                          'child_user_count' => $child_user_count,
                          'team_consume'=>$v->team_consume,
                          'status'=> $status_test,
                          'created_at'=>$v->created_at
                      ];
                      array_push($dataset, $new_row);
                      unset($new_row, $status_test, $child_user_count);
                  }
                  unset($k, $v);
              });

        $title = ['用户ID', '用户昵称', '推荐人ID','用户手机号','身份', '余额','积分','累计佣金','消费金额','团队人数', '团队业绩', '状态', '加入时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出店铺提现记录]
    public function dianpuwithdrawapplyAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $optionStartOn = $this->get('option_start_on');
        $optionEndOn = $this->get('option_end_on');
        $applyType = $this->get('apply_type');
        $query = \app\modules\Merchant\models\dianpuwalletapplyModel::query()->with(['dianpu','member']);
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($optionStartOn)) {
            $query = $query->where('updated_at', '>=', $optionStartOn);
        }
        if (!empty($optionEndOn)) {
            $query = $query->where('updated_at', '<=', $optionEndOn);
        }
        if ($mode) {
            switch ($mode) {
                case 'waiting':
                    $query = $query->where('status', 0);
                    break;
                case 'processing':
                    $query = $query->where('status', 1);
                    break;
                case 'solved':
                    $query = $query->where('status', 2);
                    break;
                case 'refuse':
                    $query = $query->where('status', -1);
                    break;
            }
        }
        if($applyType && in_array($applyType, ['bank', 'alipay', 'wechat'])){
            $query = $query->where('apply_type', $applyType);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'user_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'user_phone':
                    $query = $query->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'dianpu_id':
                    $query = $query->where('dianpu_id', $keywords);
                    break;
                case 'dianpu_name':
                    $query = $query->whereIn('dianpu_id', \app\modules\Admin\models\dianpuModel::query()->where('company_name', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $dataset = [];
        $query->select(['id', 'dianpu_id', 'member_id', 'apply_sn', 'apply_type', 'money', 'actual_money', 'charge_money', 'service_fee', 'status', 'platform', 'apply_info', 'remark', 'created_at', 'updated_at'])
              ->chunk(1000, function ($walletapply) use (&$dataset) {
                  foreach ($walletapply as $k => $v) {
                      $apply_info = !empty($v->apply_info)?json_decode($v->apply_info, true): [
                          '微信用户' => '',
                          '真实姓名' => '',
                          '开户行' => '',
                          '省' => '',
                          '市' => '',
                          '支行名称' => '',
                          '银行卡号' => '',
                          '微信ID' => '',
                          '支付宝账户' => '',
                      ];
                      if(count($apply_info)){
                          switch ($v->apply_type){
                              case 'wechat':
                                  $apply_info['real_name'] = $apply_info['微信用户'];
                                  $apply_info['card_no'] = $apply_info['微信ID'];
                                  $apply_info['bank_name'] = '';
                                  $apply_info['province'] = '';
                                  $apply_info['city'] = '';
                                  $apply_info['branch_name'] = '';
                                  break;
                              case 'alipay':
                                  $apply_info['real_name'] = $apply_info['真实姓名'];
                                  $apply_info['card_no'] = $apply_info['支付宝账户'];
                                  $apply_info['bank_name'] = '';
                                  $apply_info['province'] = '';
                                  $apply_info['city'] = '';
                                  $apply_info['branch_name'] = '';
                                  break;
                              default:
                                  $apply_info['real_name'] = $apply_info['真实姓名'];
                                  $apply_info['card_no'] = $apply_info['银行卡号'];
                                  $apply_info['bank_name'] = $apply_info['开户行'];
                                  $apply_info['province'] = $apply_info['省'];
                                  $apply_info['city'] = $apply_info['市'];
                                  $apply_info['branch_name'] = $apply_info['支行名称'];
                          }

                      }
                      array_push($dataset, [
                          'id'               => $v->id,
                          'dianpu_id'          => $v->dianpu ? $v->dianpu->id : '未知',
                          'dianpu_name'          => $v->dianpu ? $v->dianpu->name : '未知',
                          'user_id'          => $v->member ? $v->member->id : '未知',
                          'user_name'        => $v->member ? $v->member->nickname : '未知',
                          'user_phone'       => $v->member ? $v->member->phone : '未知',
                          'money'            => $v->money ?: '0',
                          'actual_money'     => $v->actual_money ?: '0',
                          'charge_money'     => $v->charge_money ?: '0',
                          'service_fee'      => $v->service_fee ? "{$v->service_fee}%" : '0',
                          'payable_money'    => bcsub($v->money, $v->charge_money, 2),
                          'apply_type_text'  => $v->apply_type_name ?: '--',
                          'apply_info_real_name'  => $apply_info['real_name'],
                          'apply_info_bank_name'  => $apply_info['bank_name'],
                          'apply_info_province'  => $apply_info['province'],
                          'apply_info_city'  => $apply_info['city'],
                          'apply_info_branch_name'  => $apply_info['branch_name'],
                          'apply_info_card_no'  => $apply_info['card_no'],
                          'created_at'       => $v->created_at ?: '--',
                          'status_name'      => $v->status_name ?: '--',
                          'updated_at'       => $v->updated_at ?: '--',
                          'remark'           => $v->remark ?: '无',
                      ]);
                  }
                  unset($k);
                  unset($v);
              });
        $title = ['ID', '申请店铺ID', '申请店铺名称', '申请用户ID', '申请用户名称', '申请用户手机号', '提现金额', '实际到帐金额', '手续费', '手续费费率', '应付金额', '提现方式', '真实姓名', '开户行', '省', '市', '支行名称', '银行卡号', '申请时间', '申请状态', '操作时间', '原因/备注'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[导出任务佣金记录]
    public function taskrewardAction()
    {
        $path = $this->get('path');
        $type = $this->get('type');
        $keywords = $this->get('keywords');
        $mode = $this->get('mode');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $query = taskrewardModel::query()->with(['member', 'buyerInfo', 'orderInfo', 'orderItemInfo']);
        if ($mode != 'all') {
            switch ($mode) {
                case 'waiting':
                    $query = $query->where('status', taskrewardModel::COMMISSION_REWARD_STATUS_WAITING);
                    break;
                case 'accounted':
                    $query = $query->where('status', taskrewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                    break;
                case 'cancel':
                    $query = $query->where('status', taskrewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                    break;
                case 'back':
                    $query = $query->where('status', taskrewardModel::COMMISSION_REWARD_STATUS_BACK);
                    break;
            }
        }
        if (!empty($startOn)) {
            $query = $query->where('created_at', '>=', $startOn);
        }
        if (!empty($endOn)) {
            $query = $query->where('created_at', '<=', $endOn);
        }
        if (!empty($keywords) && !empty($type)) {
            switch ($type) {
                case 'member_id':
                    $query = $query->where('member_id', $keywords);
                    break;
                case 'member_phone':
                    $query = $query->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'order_id':
                    $query = $query->where('order_id', $keywords);
                    break;
                case 'order_sn':
                    $query = $query->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'buyer_id':
                    $query = $query->where('buyer_id', $keywords);
                    break;
                case 'buyer_phone':
                    $query = $query->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
                case 'goods_id':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $keywords)->pluck('id')->toArray());
                    break;
                case 'goods_title':
                    $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$keywords}%")->pluck('id')->toArray());
                    break;
            }
        }
        $query = $query->orderBy('created_at', 'desc');
        $appends = ['status_name'];
        $dataset = [];
        $query->select(['id', 'order_id', 'order_item_id', 'buyer_id', 'member_id', 'type', 'commission', 'commission_level', 'status', 'created_at', 'updated_at'])
            ->chunk(1000, function ($gudongRewards) use (&$dataset, $appends) {
                if (!empty($appends)) {
                    foreach ($appends as $append) {
                        $gudongRewards = $gudongRewards->append($append);
                    }
                }
                foreach ($gudongRewards as $k => $v) {
                    array_push($dataset, [
                        'id'           => $v->id,
                        'member_id'    => $v->member ? $v->member->id : '未知',
                        'member_name'  => $v->member ? $v->member->nickname : '未知',
                        'member_phone' => $v->gudong ? $v->member->phone : '未知',
                        'buyer_id'     => $v->buyerInfo ? $v->buyerInfo->id : '未知',
                        'buyer_name'   => $v->buyerInfo ? $v->buyerInfo->nickname : '未知',
                        'buyer_phone'  => $v->buyerInfo ? $v->buyerInfo->phone : '未知',
                        'order_id'     => $v->orderInfo ? $v->orderInfo->id : '未知',
                        'order_sn'     => $v->orderInfo ? $v->orderInfo->order_sn : '未知',
                        'goods_id'     => $v->orderItemInfo ? $v->orderItemInfo->goods_id : '未知',
                        'goods_title'  => $v->orderItemInfo ? $v->orderItemInfo->goods_title : '未知',
                        'goods_sku'    => $v->orderItemInfo ? $v->orderItemInfo->goods_sku_text : '未知',
                        'goods_number' => $v->orderItemInfo ? $v->orderItemInfo->goods_num : '未知',
                        'commission'   => $v->commission,
                        'status_name'  => $v->status_name ?: '无状态',
                        'created_at'   => $v->created_at ?: '--',
                        'updated_at'   => $v->updated_at ?: '--',
                    ]);
                }
                unset($k);
                unset($v);
            });
        $title = ['ID', '会员ID', '会员名称', '会员手机号',
            '下单用户ID', '下单用户名称', '下单用户手机号',
            '订单ID', '订单编号',
            '商品ID', '商品名称', '商品规格', '商品数量',
            '分红金额', '入帐状态', '分红时间', '变动时间'];
        $this->exportExcel($title, $dataset, $path);
        echo 'Done';
    }

    #[生成excel]
    private function exportExcel($title, $data = [], $path = '')
    {
        $spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $colcounter  = count($title);
        $keys        = $data ? array_keys($data[0]) : 0;
        for ($i = 1; $i <= $colcounter; $i++) {
            $sheet->setCellValue(Coordinate::stringFromColumnIndex($i) . '1', $title[$i-1]);
        }
        $sheet->getStyle('A1:' . Coordinate::stringFromColumnIndex( $i) . '1')->getFont()->setBold(true)->setColor((new Style\Color)->setRGB('ff0000'));
        foreach ($data as $index => $row) {
            for ($j = 1; $j <= $colcounter; $j++) {
                $sheet->setCellValueExplicit(Coordinate::stringFromColumnIndex($j) . ($index + 2), $row[$keys[$j-1]], DataType::TYPE_STRING);
            }
        }
        for ($k = 1; $k <= $colcounter; $k++) {
            $sheet->getColumnDimension(Coordinate::stringFromColumnIndex($k))->setAutoSize(true);
        }
        $writer = PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save($path);
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
    }

}
